|
|
|
Shell scripts can access command-line arguments through special variables. This example demonstrates how to work with positional parameters. |
|
|
Set some arguments for demonstration: |
|
|
$0 is the script name (or shell name in interactive mode): |
|
|
\(1, \)2, etc. are positional parameters: |
|
|
$# is the number of arguments: |
|
|
$@ expands to all arguments as separate words: |
|
|
$* expands to all arguments as a single word when quoted: |
|
|
The difference matters with spaces in arguments: |
|
|
Always use “$@” (quoted) to preserve argument boundaries. |
|
|
|
|
|
Common pattern: Process all arguments with shift: |
|
|
Check if arguments were provided: |
|
|
Default values for missing arguments: |
|
|
\({var:-default} uses default if var is unset or empty \){var:=default} also assigns the default to var |
|
|
Require an argument (exit if missing): |
|
|
Arguments beyond $9 need braces: |
|
|
Check for specific number of arguments: |
|
|
Parse arguments into variables: |
|
|
$$ is the script’s process ID: |
|
|
$! is the PID of the last background command: |
|
|
Bash
Bash provides additional variables:
|
|
|
Common argument handling pattern: |
|