Special Parameters
--- CURRENT PAGE --- In BASH scripting, special variables and parameters provide critical access to command-line arguments, script metadata, and runtime context. These tools are essential for building robust scripts that interact with user input and system state.
Positional Parameters: $@ and $*¶
Positional parameters represent command-line arguments passed to a script. While both $@ and $* access all arguments, their behavior differs in expansion:
$@: Treats each argument as a separate string, preserving spaces within arguments. Ideal for iterating over arguments safely.$*: Expands to a single string with all arguments concatenated, using the first character ofIFS(typically a space) as the delimiter. Less safe for arguments with spaces.
Example¶
#!/bin/bash
echo "Arguments as \$@:"
for arg in "$@"; do
echo "$arg"
done
echo "Arguments as \$*:"
echo "$*"
Output (with input hello world 42):
Special Variables: $0, $?, and $-¶
$0 - Script Name¶
Represents the name of the script or the first argument passed to a function. Useful for logging or debugging.
$? - Exit Status¶
Stores the exit code of the last command executed. A return value of 0 indicates success, non-zero values indicate errors.
$- - Option Flags¶
Shows the current shell options (e.g., i for interactive mode, x for debug mode). Use with caution, as it may vary between shells.
Example¶
#!/bin/bash
ls /nonexistent && echo "Success" || echo "Failure"
echo "Last command exit code: $?"
echo "Script name: $0"
Output:
ls: /nonexistent: No such file or directory
Failure
Last command exit code: 2
Script name: script.sh
Command-Line Argument Handling¶
Accessing Arguments¶
$1,$2, ...$9: Access individual arguments (note:$10+ require indirect expansion).$#: Returns the number of positional arguments.
Example: Argument Count¶
Output (with input arg1 arg2):
Parsing Options with getopts¶
For complex argument parsing, use getopts to handle flags and options. This avoids issues with positional parameters and ensures consistent behavior.
Example: getopts Usage¶
#!/bin/bash
while getopts "f:o:" opt; do
case $opt in
f) filename="$OPTARG" ;;
o) output="$OPTARG" ;;
\?) echo "Invalid option: -$opt" >&2 ;;
esac
done
echo "Filename: $filename, Output: $output"
Usage:
Key takeaways¶
- Use
$@for safe iteration over arguments, and$*for concatenated strings. $0identifies the script name, while$?tracks exit codes for error handling.$-reveals shell options but is rarely used in practice.- Always validate argument counts (
$#) and usegetoptsfor structured option parsing. --- END CURRENT PAGE ---