To handle optional arguments in a Bash script, you can use the getopts command. Here's a simple example that demonstrates how to create a script that accepts optional arguments.
Step 1: Create a Bash Script
Create a new Bash script named optional_args.sh.
Step 2: Add the Code
Add the following code to optional_args.sh:
#!/bin/bash
# Default values
name="User"
age="Unknown"
# Parse optional arguments
while getopts ":n:a:" opt; do
case $opt in
n) name="$OPTARG" ;; # Set name if -n is provided
a) age="$OPTARG" ;; # Set age if -a is provided
\?) echo "Invalid option: -$OPTARG" >&2 ;;
:) echo "Option -$OPTARG requires an argument." >&2 ;;
esac
done
# Print the values
echo "Name: $name"
echo "Age: $age"
Step 3: Make the Script Executable
Run the following command to make the script executable:
chmod +x optional_args.sh
Step 4: Execute the Script
You can run the script with optional arguments like this:
./optional_args.sh -n Alice -a 30
Output
You should see the output:
Name: Alice
Age: 30
Explanation
getoptsis used to parse the options. In this case,-nfor name and-afor age.OPTARGholds the value of the argument provided for the option.- The script sets default values for
nameandageand updates them if the corresponding options are provided.
This is how you can handle optional arguments in a Bash script.
