How to Use Command Line Arguments in Bash Scripts
In Bash, command line arguments are accessed using special variables like
$1, $2, etc., where $1 is the first argument. The total number of arguments is stored in $#, and all arguments together are in $@.Syntax
In a Bash script, command line arguments are accessed using positional parameters:
$0: The script name.$1,$2, ...: The first, second, and subsequent arguments.$#: Number of arguments passed.$@: All arguments as separate words.$*: All arguments as a single string.
bash
script.sh arg1 arg2 arg3 # Inside script.sh # $0 = script.sh # $1 = arg1 # $2 = arg2 # $3 = arg3 # $# = 3 # $@ = arg1 arg2 arg3 # $* = arg1 arg2 arg3
Example
This example script prints each command line argument with its position and shows the total count.
bash
#!/bin/bash echo "Script name: $0" echo "Number of arguments: $#" count=1 for arg in "$@" do echo "Argument $count: $arg" ((count++)) done
Output
Script name: ./example.sh
Number of arguments: 3
Argument 1: apple
Argument 2: banana
Argument 3: cherry
Common Pitfalls
Common mistakes include:
- Not quoting
$@which can cause arguments with spaces to split incorrectly. - Using
$*without quotes, which concatenates all arguments into one string. - Accessing arguments beyond
$#which are empty.
Always quote variables like "$@" to preserve argument boundaries.
bash
# Wrong way (arguments with spaces break): for arg in $@ do echo "$arg" done # Right way: for arg in "$@" do echo "$arg" done
Quick Reference
| Variable | Meaning |
|---|---|
| $0 | Script name |
| $1, $2, ... | First, second, etc. arguments |
| $# | Number of arguments |
| $@ | All arguments as separate words |
| $* | All arguments as a single string |
Key Takeaways
Use $1, $2, etc., to access individual command line arguments in Bash.
Always quote "$@" when looping over arguments to handle spaces correctly.
Use $# to check how many arguments were passed to your script.
Avoid using $* without quotes as it merges all arguments into one string.
Remember $0 holds the script's name, not an argument.