My Bash Scripting Notes — All the basics at one place

Bhavyansh @ DiversePixel
4 min readJun 1, 2024

--

This is my Bash Scripting Notes, tried to write down every important detail. I hope you derive value from it✌️🤝

Photo by Alex Chumak on Unsplash

1. Basic Script Structure

Shebang: Every script starts with #!/bin/bash, telling the system to use the bash interpreter. (e.g., 1_firstscript.sh)

Comments: Use # for single-line comments to explain your code.

Commands: Scripts execute commands sequentially, like in a terminal. (e.g., echo, uptime, free, df)

2. Output and Display

echo: Prints text to the console. (e.g., echo “Welcome to bash script.”)

Quotes: Single quotes treat content literally, while double quotes allow variable expansion. (e.g., echo “Welcome $USER” vs. echo ‘Welcome $USER’)

3. Variables

Declaration: No data type declaration needed, just assign a value. (e.g., TEMPDIR=”/tmp/webfiles”)

Access: Use $ before the variable name. (e.g., echo $TEMPDIR)

Command Substitution: Enclose a command in $(…) to capture its output and assign it to a variable. (e.g., FREERAM=$(free -m | grep Mem | awk ‘{print $4}’)

4. User Input

read: Reads input from the user and stores it in a variable. (e.g., read SKILL)

Prompt: Use -p flag with read to display a prompt message. (e.g., read -p ‘Username: ‘ USR)

Hidden Input: Use -s flag with read for passwords. (e.g., read -sp ‘Password: ‘ pass)

5. Conditional Statements

if: Executes a block of code if the condition is true. (e.g., if [ $NUM -gt 100 ])

else: Provides an alternative code block if the if condition is false.

elif: Chains multiple conditions. (e.g., elif [ $value -gt 1 ])

Comparison Operators:

  • -eq: Equal to
  • -ne: Not equal to
  • -gt: Greater than
  • -lt: Less than
  • -ge: Greater than or equal to
  • -le: Less than or equal to

File Test Operators:

  • -f: Check if file exists and is a regular file

6. Loops

for: Iterates over a list of values.

while: Executes a block of code as long as the condition is true.

Condition-based: (e.g., while [ $counter -lt 5 ])

Infinite loop: Use while true to create a loop that runs indefinitely until explicitly stopped.

7. Exit Status

$?: Holds the exit status of the last executed command (0 for success, non-zero for failure). (e.g., if [ $? -eq 0 ])

8. Script Arguments

$0, $1, $2, …: Access script arguments by their position. $0 is the script name itself.

Passing Arguments: Provide arguments after the script name when executing. (e.g., ./my_script.sh arg1 arg2)

9. Redirection and Pipes

>: Redirects output to a file, overwriting the file if it exists. (e.g., sudo yum install wget unzip httpd -y > /dev/null)

>>: Appends output to a file.

|: Pipes the output of one command as input to another. (e.g., free -m | grep Mem | awk ‘{print $4}’)

10. Example Use Cases

System Administration: Automate tasks like installing software, managing services (starting, stopping), monitoring system resources, and deploying applications.

Web Development: Deploy websites, manage web servers, and automate web-related tasks.

Data Processing: Process text files, extract information, and manipulate data using commands like grep, awk, sed.

11. Best Practices

  • Use meaningful variable names.
  • Comment your code thoroughly.
  • Validate user input to prevent errors.
  • Test your scripts thoroughly.
  • Consider using functions to organize code into reusable blocks.
  • Use appropriate error handling techniques.

Sample script:

#!/bin/bash
# 1. Basic Script Structure
# Shebang

# Comments: This script demonstrates various bash scripting concepts.

# 2. Output and Display
echo "Welcome to the mega bash script demo."
# Single vs Double Quotes
echo "Current user: $USER"
echo 'Current user: $USER'

# 3. Variables
TEMPDIR="/tmp/webfiles"
echo "Temporary directory is $TEMPDIR"
# Command Substitution
FREERAM=$(free -m | grep Mem | awk '{print $4}')
echo "Free RAM: ${FREERAM}MB"

# 4. User Input
read -p "Enter your name: " USERNAME
read -sp "Enter your password: " PASSWORD
echo
echo "Hello, $USERNAME"

# 5. Conditional Statements
read -p "Enter a number: " NUM
if [ "$NUM" -gt 100 ]; then
echo "The number is greater than 100"
elif [ "$NUM" -gt 50 ]; then
echo "The number is greater than 50 but less than or equal to 100"
else
echo "The number is 50 or less"
fi

# File Test Operators
if [ -f "$TEMPDIR/sample.txt" ]; then
echo "sample.txt exists."
else
echo "sample.txt does not exist."
fi

# 6. Loops
for VAR in java .net python ruby php; do
echo "Learning $VAR"
done
counter=0
while [ "$counter" -lt 5 ]; do
echo "Counter: $counter"
((counter++))
done

# Infinite Loop
# Uncomment the below lines to test the infinite loop
# while true; do
# echo "Press [CTRL+C] to stop.."
# sleep 1
# done

# 7. Exit Status
echo "Checking if /tmp directory exists."
ls /tmp
if [ $? -eq 0 ]; then
echo "/tmp directory exists."
else
echo "/tmp directory does not exist."
fi

# 8. Script Arguments
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
# Usage: ./mega_script.sh arg1 arg2

# 9. Redirection and Pipes
echo "Creating a directory structure in $TEMPDIR"
mkdir -p $TEMPDIR
# Redirect output to a file
echo "Installation logs" > $TEMPDIR/install.log
# Append output to a file
echo "Appending a new line" >> $TEMPDIR/install.log
# Pipes
df -h | grep "/dev/sda1" > $TEMPDIR/disk_usage.txt

# 10. Example Use Cases
# System Administration Example
echo "Installing software (simulated)…"
# sudo yum install wget unzip httpd -y > /dev/null
# Web Development Example
echo "Setting up web server (simulated)…"
# sudo systemctl start httpd
# Data Processing Example
echo "Processing data (simulated)…"
# grep "pattern" file.txt | awk '{print $1}'

# 11. Best Practices
# Meaningful variable names, thorough commenting, user input validation, testing, functions, and error handling.
# Example function
function greet_user {
echo "Hello, $1!"
}

greet_user $USERNAME

# Error handling example
function check_file {
if [ -f "$1" ]; then
echo "File $1 exists."
else
echo "File $1 does not exist."
fi
}

check_file "$TEMPDIR/sample.txt"

Any suggestions are welcome. Let’s make this as complete as we can make keeping brevity in check.

--

--

Bhavyansh @ DiversePixel
Bhavyansh @ DiversePixel

Written by Bhavyansh @ DiversePixel

Hey I write about Tech. Join me as I share my tech learnings and insights. 🚀

No responses yet