How to Write a Simple Bash Script on Linux
Write your first Bash script from scratch — shebang line, variables, conditionals, loops, and how to make it executable and run it.
What Is a Bash Script?
A Bash script is a text file containing shell commands that are executed in sequence. Scripts let you automate repetitive tasks, set up servers, process files, and anything else you'd do manually in the terminal.
Step 1 — Create the Script File
nano ~/scripts/hello.sh
Step 2 — Add the Shebang Line
The first line of every Bash script tells the OS which interpreter to use:
#!/bin/bash
This is called the shebang. Always include it.
Step 3 — Variables
Variables are set without spaces around = and referenced with $:
#!/bin/bash
NAME="Alice"
TODAY=$(date +%Y-%m-%d) # command substitution
echo "Hello, $NAME!"
echo "Today is $TODAY"
Step 4 — User Input
#!/bin/bash
echo "What is your name?"
read NAME
echo "Hello, $NAME!"
Step 5 — Conditionals
#!/bin/bash
FILE="/etc/passwd"
if [ -f "$FILE" ]; then
echo "$FILE exists"
else
echo "$FILE not found"
fi
Common test operators: -f (file exists), -d (directory), -z (empty string), -eq (equal numbers), -gt (greater than).
Step 6 — Loops
# Loop over a list
for FRUIT in apple banana cherry; do
echo "I like $FRUIT"
done
# Loop over files
for FILE in ~/Documents/*.txt; do
echo "Processing: $FILE"
done
# While loop
COUNT=1
while [ $COUNT -le 5 ]; do
echo "Count: $COUNT"
((COUNT++))
done
Step 7 — Make It Executable and Run It
chmod +x ~/scripts/hello.sh # make executable
~/scripts/hello.sh # run it
Or run it explicitly with bash: bash ~/scripts/hello.sh
A Practical Example: Backup Script
#!/bin/bash
SOURCE="$HOME/Documents"
DEST="$HOME/backups"
DATE=$(date +%Y-%m-%d)
mkdir -p "$DEST"
tar -czf "$DEST/docs-$DATE.tar.gz" "$SOURCE"
echo "Backup created: $DEST/docs-$DATE.tar.gz"
Script Best Practices
- Always start with
#!/bin/bash - Add
set -eat the top to stop on any error - Quote variables:
"$VAR"not$VAR— prevents word-splitting bugs - Test your script on sample data before running on production