Writing Bash Scripts
Harry
· 14 Sep 2026
· 1 views
Advertisement
Your first script
A Bash script is a text file of commands. The first line, the shebang, tells the system which interpreter to use:
#!/bin/bash
echo "Backing up..."
cp -r /data /backup
echo "Done"
chmod +x backup.sh # make it executable
./backup.sh # run it
Variables and arguments
#!/bin/bash
name="Ada"
echo "Hello, $name"
# arguments passed on the command line
echo "First arg: $1"
echo "All args: $@"
Use $name to read a variable; script arguments are $1, $2 and so on. Always quote variables ("$name") to avoid word-splitting bugs.
Conditionals
if [ -f "$1" ]; then
echo "$1 exists"
elif [ -d "$1" ]; then
echo "$1 is a directory"
else
echo "not found"
fi
Common tests: -f (file exists), -d (directory), -z (empty string), and -eq/-gt for numbers.
Loops
# loop over files
for f in *.txt; do
echo "Processing $f"
done
# loop while a condition holds
count=1
while [ $count -le 5 ]; do
echo $count
count=$((count + 1))
done
Making scripts robust
Start real scripts with set -euo pipefail: exit on any error (-e), treat unset variables as errors (-u), and fail if any command in a pipe fails (-o pipefail). This turns silent failures into loud, debuggable ones.
Key points
- Start scripts with
#!/bin/bashand make them executable withchmod +x. - Read variables with
$nameand arguments with$1,$@; quote them. - Use
ifwith tests like-f/-d, andfor/whileloops. - Add
set -euo pipefailto make scripts fail fast and safely.