Skip to content
AgileLogics
5 min read

Script Arguments

Prerequisites: Variables, Quoting

Scripts become reusable when they accept arguments — the words typed after the script's name.

Variable Holds
$0 the script's name
$1, $2, ... the first, second, ... argument
$# the number of arguments
"$@" all arguments, each kept separate

Example

cat > greet.sh <<'EOF'
#!/usr/bin/env bash
echo "Script: $0"
echo "You passed $# argument(s)"
echo "First: $1"
echo "Second: $2"
for arg in "$@"; do
  echo "- $arg"
done
EOF

bash greet.sh Ada "Grace Hopper"
Script: greet.sh
You passed 2 argument(s)
First: Ada
Second: Grace Hopper
- Ada
- Grace Hopper

Quoting "Grace Hopper" made it one argument, and "$@" kept it together in the loop. (The 'EOF' in quotes stops the here document from expanding $0 and friends while writing the file.)

Checking for required arguments

cat > backup.sh <<'EOF'
#!/usr/bin/env bash
if [ $# -lt 1 ]; then
  echo "Usage: $0 <folder>" >&2
  exit 1
fi
echo "Backing up $1..."
EOF

bash backup.sh
echo "exit code: $?"
bash backup.sh photos
Usage: backup.sh <folder>
exit code: 1
Backing up photos...
  • A usage message tells people how to run the script.
  • >&2 sends the message to stderr, where errors belong.
  • exit 1 stops with a failure status. (if is explained properly in the next lessons.)

Default values

${1:-default} uses a default when an argument is missing:

cat > hello.sh <<'EOF'
name=${1:-world}
echo "Hello, $name!"
EOF

bash hello.sh
bash hello.sh Ada
Hello, world!
Hello, Ada!

Common mistakes

  • Using $* or unquoted $@ — both break arguments containing spaces. Use "$@".
  • Forgetting that arguments are text: $1 holding "10" still needs $(( )) for arithmetic.