When writing shell scripts, one of the most common sources of confusion is positional parameters — the $1, $2, $3 variables that represent arguments passed to a script or function. Let’s walk through a real example to make this crystal clear.
The Script:
#!/bin/bash
backup(){
backup_name="${1}_$(date +%F_%H-%M-%S).tar.gz"
if tar -czf "$backup_name" "$1"; then
echo "✅ Backup created: $backup_name"
else
echo "❌ Backup failed for $1"
fi
}
list(){
find . -type f -name "*.tar.gz"
}
case $1 in
back)
backup "$2"
;;
list)
list
;;
*)
echo "Usage:"
echo " $0 back <directory_or_file>"
echo " $0 list"
;;
esac
How It Works
Step 1: Script Arguments
When you run:
./backup-manager.sh back dir21
$0 → ./backup-manager.sh (the script name)
$1 → back
$2 → dir21
The case statement checks $1. Since it’s back, the script calls:
backup "$2"
Step 2: Function Arguments
Now the function backup() is called with one argument: dir21.
Inside the function:
$1 → dir21 (because $1 inside a function refers to the first argument passed to that function, not the script’s $1 anymore).
That’s why you see $2 in the script but $1 inside the function — they’re different scopes.
Example Run
$ ./backup-manager.sh back dir21
✅ Backup created: dir21_2026-04-03_09-25-00.tar.gz
$ ./backup-manager.sh list
./dir21_2026-04-03_09-25-00.tar.gz
Key Takeaways
Script arguments ($1, $2, …) are what the user types after the script name.
Function arguments ($1, $2, … inside the function) are what you pass when calling the function.
They are independent: $1 in the script is not the same as $1 inside the function.
Bonus Tip: Multiple Backups
You can extend the script to back up multiple directories at once:
case $1 in
back)
shift # remove "back" from arguments
for target in "$@"; do
backup "$target"
done
;;
list)
list
;;
*)
echo "Usage: $0 back <dir1> <dir2> ... | $0 list"
;;
esac
Now you can run: ./backup-manager.sh back dir21 dir22 dir23
and it will back up all three.
💡 This is a great example to blog about because it shows the layered nature of arguments in Bash — script level vs function level — and clears up a common beginner confusion.
Top comments (0)