How to handle optional arguments?

0135

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

  • getopts is used to parse the options. In this case, -n for name and -a for age.
  • OPTARG holds the value of the argument provided for the option.
  • The script sets default values for name and age and updates them if the corresponding options are provided.

This is how you can handle optional arguments in a Bash script.

0 Comments

no data
Be the first to share your comment!