Understanding Script vs Function Arguments in Bash
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 throu...

Source: DEV Community
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