Why Learn Bash Scripting?
Bash (Bourne Again SHell) is the default shell on most Linux distributions and macOS. Learning to write Bash scripts lets you automate repetitive tasks, batch process files, schedule jobs, and manage systems far more efficiently than clicking through GUIs. Even a basic script that saves five minutes a day adds up to hours saved each month.
1. Your First Script
Every Bash script starts with a shebang line that tells the system which interpreter to use:
#!/bin/bash
echo "Hello, Linux world!"
Save this as hello.sh, make it executable with chmod +x hello.sh, and run it with ./hello.sh.
2. Variables
Variables store data for use later in the script. No spaces around the = sign:
NAME="Alice"
AGE=30
echo "Name: $NAME, Age: $AGE"
Use $variable or ${variable} to reference a variable. The curly brace form is safer when concatenating strings: ${NAME}_backup.tar.gz.
3. Reading User Input
The read command captures input from the user:
echo "Enter your username:"
read USERNAME
echo "Welcome, $USERNAME!"
4. Conditionals (if/else)
Use if statements to make decisions. Note the spaces inside the brackets — they're required:
if [ -f "/etc/passwd" ]; then
echo "The file exists."
else
echo "File not found."
fi
Common test operators:
-f file— file exists and is a regular file-d dir— directory exists-z "$var"— string is empty-n "$var"— string is not empty$a -eq $b— numbers are equal$a -gt $b— a is greater than b
5. Loops
For Loop
for FILE in /var/log/*.log; do
echo "Processing: $FILE"
done
While Loop
COUNT=1
while [ $COUNT -le 5 ]; do
echo "Iteration $COUNT"
((COUNT++))
done
6. Functions
Functions let you group reusable logic and call it by name:
greet_user() {
local USER=$1
echo "Hello, $USER! Today is $(date +%A)."
}
greet_user "Bob"
greet_user "Carol"
Use $1, $2, etc. to access positional arguments inside a function. The local keyword scopes the variable to the function.
7. Practical Example: Backup Script
Here's a simple script combining everything above — it backs up a directory with a timestamp:
#!/bin/bash
SOURCE_DIR="/home/alice/documents"
BACKUP_DIR="/mnt/backup"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/docs_backup_$TIMESTAMP.tar.gz"
if [ ! -d "$SOURCE_DIR" ]; then
echo "Error: Source directory not found."
exit 1
fi
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_FILE" "$SOURCE_DIR"
echo "Backup created: $BACKUP_FILE"
Best Practices
- Always use
#!/bin/bash(not#!/bin/sh) when using Bash-specific features. - Quote your variables:
"$VAR"prevents word splitting and glob expansion issues. - Use
set -eat the top to exit immediately on any error. - Use
set -uto treat unset variables as errors. - Test your scripts with
bash -n script.shto check for syntax errors before running. - Add comments (
#) to explain non-obvious logic.
Bash scripting rewards practice. Start with small automation tasks — renaming files, cleaning up logs, checking disk space — and gradually tackle more complex workflows.