Working with Command Line Arguments ($1, $2...)
Summary: Pass and process arguments in scripts.
When writing shell scripts in Bash or other Unix-like shells, you will often want to make your scripts flexible and reusable by passing information to them. This is achieved through command line arguments. Let’s explore how to pass and process these arguments in scripts, focusing on positional parameters like $1
, $2
, etc.
Introduction to Command Line Arguments
A command line argument is simply input provided after the script’s name when running it. Suppose you have a script called greet.sh
:
./greet.sh Alice
Here, Alice
is the first argument to the script.
Positional Parameters: What Are $1, $2, ...?
In the script, $1
refers to the first argument, $2
to the second, and so on. The special variable $0
holds the name of the script itself.
Example
Let’s create a script called add.sh
:
#!/bin/bash
echo "First number: $1"
echo "Second number: $2"
sum=$(( $1 + $2 ))
echo "Sum: $sum"
Run it as:
./add.sh 7 13
Output:
First number: 7
Second number: 13
Sum: 20
Useful Special Variables
$0
– Name of the script or command$1, $2
, ... – The first, second, etc., argument$#
– The number of arguments passed$@
– All arguments, treated as separate words$*
– All arguments, as a single word
Working With Many Arguments
If your script accepts more than 9 arguments, reference them like this: ${10}
, ${11}
, etc.
echo "Tenth arg is: ${10}"
Looping Through All Arguments
You can iterate over all provided arguments using a loop:
#!/bin/bash
echo "All arguments:"
for arg in "$@"; do
echo "$arg"
done
Checking for Required Arguments
You often want your scripts to check if enough arguments are provided:
#!/bin/bash
if [ "$#" -lt 2 ]; then
echo "Usage: $0 arg1 arg2"
exit 1
fi
echo "All checks passed. Proceeding..."
Quoting Arguments
Always quote variables (e.g., "$1"
) to prevent errors if arguments contain spaces or special characters:
echo "Hello, $1!" # Bad: may misbehave with spaces
echo "Hello, \"$1\"!" # Good: works with spaces
Advanced: Processing with Shift
The shift
command moves all arguments one position to the left, so $2
becomes $1
, etc.
#!/bin/bash
while [ "$#" -gt 0 ]; do
echo "Processing argument: $1"
shift
done
Conclusion
Mastering command line arguments is key to writing powerful and reusable shell scripts. By understanding how $1
, $2
, and related variables work, you can easily pass and process information, handle multiple inputs, and make your scripts efficient and user-friendly.
Further Reading
- GNU Bash Manual: Shell Parameters
man bash
on your terminal
Happy scripting!