Command-line arguments provide a way to pass inputs to a shell script during its execution. This guide explores the processing of command-line arguments, including handling options and flags.
Shell scripts can accept command-line arguments, which are provided after the script name during execution. The positional parameters $1, $2, etc., represent these arguments.
#!/bin/bash
# Process command-line arguments
echo "First argument: $1"
echo "Second argument: $2"
echo "Number of arguments: $#"
echo "All arguments: $@"In this example, the script prints the first and second command-line arguments, the total number of arguments, and all arguments provided.
#!/bin/bash
# Iterate through command-line arguments
for arg in "$@"; do
echo "Argument: $arg"
doneHere, the script uses a for loop to iterate through all command-line arguments provided.
Options and flags provide a way to modify the behavior of a script by specifying certain parameters during execution.
#!/bin/bash
# Process options using getopts
while getopts ":a:b:" opt; do
case $opt in
a)
echo "Option 'a' with value: $OPTARG"
;;
b)
echo "Option 'b' with value: $OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG"
;;
esac
doneIn this example, the script uses getopts to process options (-a and -b) and their corresponding values.
#!/bin/bash
# Process flags
verbose=false
debug=false
while [ $# -gt 0 ]; do
case "$1" in
-v|--verbose)
verbose=true
;;
-d|--debug)
debug=true
;;
*)
echo "Invalid argument: $1"
exit 1
;;
esac
shift
done
echo "Verbose mode: $verbose"
echo "Debug mode: $debug"Here, the script processes flags (-v or --verbose and -d or --debug) to enable or disable certain features.
- Processing Command-Line Arguments: Use special variables like
$1,$2, etc., and$@to access command-line arguments. - Options and Flags: Utilize tools like getopts for handling options with values, and use conditional checks for processing flags.
These examples showcase how to effectively process command-line arguments, options, and flags in shell scripting. Experiment with different combinations to meet your script's requirements.