Writing Bash Scripts

Harry · 14 Sep 2026 · 1 views
Advertisement
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/bash and make them executable with chmod +x.
  • Read variables with $name and arguments with $1, $@; quote them.
  • Use if with tests like -f/-d, and for/while loops.
  • Add set -euo pipefail to make scripts fail fast and safely.
Share this post:

Comments (0)

Please login or register to comment.