Accessing and Parsing Command-Line Arguments
Now that you understand the concept of command-line arguments, let's dive into how to access and parse them in your Shell scripts.
Accessing Command-Line Arguments
As mentioned earlier, the shell environment automatically assigns the command-line arguments to special variables. You can access these variables within your script to perform various operations.
Here's an example script that demonstrates how to access the command-line arguments:
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"
echo "All arguments: $@"
echo "Number of arguments: $#"
Save this script as example.sh
and make it executable with the command chmod +x example.sh
. Then, run the script with some command-line arguments:
$ ./example.sh apple banana cherry
Script name: ./example.sh
First argument: apple
Second argument: banana
All arguments: apple banana cherry
Number of arguments: 3
Parsing Command-Line Arguments
In some cases, you may need to parse the command-line arguments to extract specific information or perform specific actions based on the arguments provided. This can be done using various techniques, such as using case
statements or getopts
(a built-in command in Bash for parsing command-line arguments).
Here's an example script that uses getopts
to parse command-line arguments:
#!/bin/bash
while getopts ":n:a:h" opt; do
case $opt in
n)
name=$OPTARG
echo "Name: $name"
;;
a)
age=$OPTARG
echo "Age: $age"
;;
h)
echo "Usage: $0 [-n name] [-a age]"
exit 0
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
esac
done
shift $((OPTIND - 1))
echo "Remaining arguments: $@"
Save this script as parse_args.sh
and make it executable with the command chmod +x parse_args.sh
. Then, run the script with some command-line arguments:
$ ./parse_args.sh -n John -a 30 extra_arg
Name: John
Age: 30
Remaining arguments: extra_arg
By understanding how to access and parse command-line arguments, you can create more flexible and powerful Shell scripts that can adapt to different user requirements and scenarios.