
A Bash script is a text file of commands that you run as one. Once you can write one, the boring parts of server work (backups, log checks, repeated setup) become a command you run in one second, or a job that runs by itself. This guide takes you from your first script to a small, safe backup script that you can use as it is, with the real output of every example.
Everything here was run with Bash 5.1, the version on current Red Hat, Rocky Linux and AlmaLinux systems. It works the same on Ubuntu, Debian and macOS (macOS ships an older Bash 3.2, so a few modern features such as mapfile need a newer one installed).
Your first script
Create a file called hello.sh:
#!/usr/bin/env bash
name="${1:-world}"
echo "Hello, $name!"
echo "Script: $0, arguments: $#, all: $*"
Make it executable and run it:
chmod +x hello.sh
./hello.sh
./hello.sh Sara Ahmed
Output:
Hello, world!
Script: ./hello.sh, arguments: 0, all:
Hello, Sara!
Script: ./hello.sh, arguments: 2, all: Sara Ahmed
#!/usr/bin/env bash(the shebang) tells the system which program runs the file.chmod +xgives the file the executable permission. Without it you can still runbash hello.sh.$1,$2are the arguments.$#is how many,$*is all of them, and$0is the script name.${1:-world}means “use the first argument, orworldif it is missing”.
Variables and quoting
name="Sara" # no spaces around =
echo "Hi $name" # double quotes expand variables
echo 'Hi $name' # single quotes print it literally
today=$(date +%F) # command substitution: capture output
echo "Today is $today"
Always put variables in double quotes. Without quotes, Bash splits the value on spaces. Here is what happens with a file called my file.txt:
f="my file.txt"
touch "$f"
ls -1 $f # two words: fails
ls -1 "$f" # one word: works
ls: cannot access 'my': No such file or directory
ls: cannot access 'file.txt': No such file or directory
my file.txt
This one habit prevents most scripting accidents, including the classic rm -rf $dir/ that deletes the wrong thing when $dir is empty.
Conditions
Use [[ ... ]] for tests in Bash. It is safer and more capable than the older [ ... ].
if [[ -f hello.sh && -x hello.sh ]]; then
echo "hello.sh exists and is executable"
fi
if [[ "abc" == a* ]]; then
echo "pattern match works in [[ ]]"
fi
| Test | True when |
|---|---|
-f file |
the file exists and is a regular file |
-d dir |
the directory exists |
-x file |
the file is executable |
-z "$s" / -n "$s" |
the string is empty / not empty |
"$a" == "$b" |
the strings are equal |
$n -gt 5, -lt, -eq |
number comparisons |
Loops
for n in 1 2 3; do echo "number $n"; done
for f in *.sh; do echo "script file: $f"; done
count=3
while [[ $count -gt 0 ]]; do
echo "countdown $count"
((count--))
done
number 1
number 2
number 3
script file: hello.sh
script file: loops.sh
countdown 3
countdown 2
countdown 1
To read a file line by line, use while read and keep the -r so backslashes are not eaten:
while IFS= read -r line; do
echo "line: $line"
done < servers.txt
Functions
greet() { local who="$1"; echo "Hi $who"; return 0; }
is_even() { (( $1 % 2 == 0 )); }
greet Sara
if is_even 4; then echo "4 is even"; fi
if ! is_even 5; then echo "5 is odd"; fi
result=$(greet Omar)
echo "captured: $result"
Hi Sara
4 is even
5 is odd
captured: Hi Omar
local keeps a variable inside the function. Functions return a status (0 for success), not a value. To return text, print it and capture it with $(...), as with result above.
Exit codes
Every command ends with a number called its exit code. 0 means success and anything else means failure. The last one is stored in $?:
false; echo "exit code of false: $?"
true; echo "exit code of true: $?"
ls /nonexistent 2>/dev/null; echo "exit code of failed ls: $?"
exit code of false: 1
exit code of true: 0
exit code of failed ls: 2
Your own script should exit with exit 0 on success and a non-zero number on error. Schedulers, monitoring tools and other scripts read that number.
Make scripts fail safely: set -euo pipefail
By default Bash keeps going after an error. Put this near the top of a script to make it stop instead:
set -euo pipefail
-eexits when a command fails.-utreats an undefined variable as an error.-o pipefailmakes a pipeline fail if any part of it fails, not just the last.
You can see each of them work:
$ bash -c 'set -e; echo before; false; echo after'
before # "after" never prints; the script stops
$ bash -c 'set -u; echo "$undefined_var"'
bash: line 1: undefined_var: unbound variable
$ bash -c 'false | true; echo "no pipefail: $?"'
no pipefail: 0 # the failure was hidden
$ bash -c 'set -o pipefail; false | true; echo "pipefail: $?"'
pipefail: 1 # the failure is reported
These options are not magic. set -e does not trigger inside an if condition or after ||, so it is a safety net, not a replacement for checking important commands yourself.
A real script: back up a folder and keep the newest copies
This script puts everything above to work. It makes a timestamped .tar.gz of a folder and deletes all but the newest few.
#!/usr/bin/env bash
set -euo pipefail
src="${1:?usage: backup.sh SOURCE_DIR DEST_DIR [KEEP]}"
dest="${2:?usage: backup.sh SOURCE_DIR DEST_DIR [KEEP]}"
keep="${3:-3}"
[[ -d "$src" ]] || { echo "error: $src is not a directory" >&2; exit 1; }
mkdir -p "$dest"
stamp=$(date +%Y%m%d-%H%M%S)
archive="$dest/$(basename "$src")-$stamp.tar.gz"
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
tar -czf "$tmp" -C "$(dirname "$src")" "$(basename "$src")"
mv "$tmp" "$archive"
echo "created $archive ($(du -h "$archive" | cut -f1))"
# keep only the newest $keep archives
mapfile -t old < <(ls -1t "$dest"/"$(basename "$src")"-*.tar.gz | tail -n +"$((keep + 1))")
for f in "${old[@]}"; do rm -- "$f"; echo "removed old $f"; done
Running it five times with KEEP set to 3:
$ ./backup.sh data bk 3
created bk/data-20261117-085943.tar.gz (4.0K)
...
created bk/data-20261117-085946.tar.gz (4.0K)
removed old bk/data-20261117-085943.tar.gz
created bk/data-20261117-085947.tar.gz (4.0K)
removed old bk/data-20261117-085944.tar.gz
$ ls bk | wc -l
3
And the error handling:
$ ./backup.sh
./backup.sh: line 3: 1: usage: backup.sh SOURCE_DIR DEST_DIR [KEEP]
$ ./backup.sh /nope bk ; echo "exit: $?"
error: /nope is not a directory
exit: 1
What the script teaches:
${1:?message}stops with a message when an argument is missing.trap '...' EXITruns cleanup code when the script ends, however it ends.- It writes to a temporary file first and then moves it into place, so a half-written archive never looks like a good one.
- Errors go to standard error (
>&2) and the exit code is non-zero.
Run it automatically
To run the backup every night at 02:30 with cron, open your crontab with crontab -e and add:
30 2 * * * /home/admin/backup.sh /var/www /home/admin/backups 7 >> /home/admin/backup.log 2>&1
Always use full paths in cron, because it does not run with your normal environment. On modern distributions you can also use a systemd timer instead; see our systemd guide.
Debugging a script
bash -x script.shprints every command with its values as it runs. Addset -xinside the script to trace only part of it.bash -n script.shchecks the syntax without running anything.- ShellCheck is a free tool that reads your script and points out quoting mistakes and other traps. It is available as a package on most distributions and in an online version.
Habits that keep scripts safe
- Quote every variable:
"$var". - Start with
set -euo pipefail, and check important commands yourself. - Use
${var:?}before anyrmso an empty variable stops the script instead of deleting the wrong folder. - Test on copies of your data, and print the command (
echo rm ...) before you let it run for real. - Use full paths in cron jobs, and send output to a log file.
- Keep scripts in version control. See how to undo mistakes in Git if you slip.
Once these basics feel natural, our Linux commands guide gives you the building blocks (find, grep, awk, sed) to put inside your scripts.
More tutorials like this
Linux Permission Denied Error: Causes and How to Fix It (chmod, namei, id)
Fix the Linux Permission denied error: read ls -l, namei -l and id, then add only the permission letter you need with chmod. Real…
systemd Basics: Manage Services and Read Logs with systemctl and journalctl
Start, stop and enable services with systemctl, read logs with journalctl, write your own service and timer, and troubleshoot a service that will not…
Linux Processes: ps, top, kill, nice and Background Jobs Explained
List and sort processes with ps and top, stop them safely with kill signals, set priority with nice, and keep long jobs running with…


