A fully functional Bash script may require optional arguments. They provide flexibility and customization of a script. Positional parameters are the default way to parse arguments in a Bash script. However, just simple positional parameters can’t handle optional arguments. Users must know how to set the default value of a positional parameter or use the getopts command to successfully parse optional arguments. This article will discuss two methods to parse optional arguments in a Bash script.
What Does Optional Argument in Bash Script Mean?
An optional argument in a Bash script refers to a command-line argument that users can provide while executing the script. However, it is not mandatory for the functionality of the script. Though not required, optional arguments offer flexibility by allowing users to customize the behavior of the script.
2 Ways to Add Optional Argument in Bash Script
There are mainly two ways to add the functionality of passing optional arguments in a Bash script. The first one includes the use of positional parameters with default values. And, the other is using the getopts command to add optional arguments in a Bash script.
1. Positional Parameters with Default Value
Positional parameters are primarily used for parsing and retrieving command-line arguments in Bash. You can make an argument optional by setting a default value for its corresponding positional parameter. For example, if you want to make the second argument optional and set a default value use the syntax, "${2:-default_value}"
The following example features a Bash script for copying files, where the source file is mandatory but the destination directory is set optional with the help of the default value of the positional parameter:
#!/bin/bash
filename="$1" # First argument
destination="${2:-temp}" # Optional second argument
if [ -z "$filename" ]; then
echo "Error: Please provide a filename."
exit 1
fi
cp "$filename" "$destination"
echo "File copied to $destination"
This Bash script copies a file specified by the first argument ($1) to a destination directory specified by an optional second argument ($2). The default directory should be “temp” if the second argument is not provided. The program first checks if a filename is provided; if not, it displays an error message and exits with status code 1. Then, it performs the copy operation using the cp command, copying the file to the specified destination directory. Finally, it outputs a message confirming the successful copy operation, indicating the destination directory where the file was copied.
In the first execution, backup/ is provided as the second argument of the script. As a result, “file1.txt” is copied to the “backup/” directory. However, in the following execution, no directory is provided as the second argument. Automatically, the script uses the default value for the second argument and copies the “file1.txt” to the “temp” folder. This makes the second argument optional for the above script.
2. Using “getopts” Command
The getopts command is a shell built-in Bash for parsing command-line options and arguments. The following script demonstrates how to process optional arguments in Bash script using the getopts command:
#!/bin/bash
destination="temp"
# Parse command-line options
while getopts ":f:d:" opt; do
case $opt in
f) filename="${OPTARG}"
;;
d) destination="${OPTARG}"
;;
esac
done
# Check if the filename is provided
if [ -z "$filename" ]; then
echo "Error: You must provide a filename using the -f option." >&2
exit 1
fi
# Copy the file to the destination
cp "$filename" "$destination"
echo "File copied to $destination"
This Bash script initializes a variable destination
with the value “temp” and then uses the getopts command to parse command-line options. It expects two options: -f
for specifying the filename and -d
for specifying the destination directory. If the -f option is not provided with a filename, it prints an error message and exits. After parsing the options, it uses the cp command to copy the file specified by the -f option to the destination directory specified by the -d option (or the default “temp” directory if not provided). Finally, it prints a message confirming the file has been copied to the destination.
When “backup” is provided as an argument after the option -d, “file1.txt” is copied to the “backup” directory. On the other hand, when a directory isn’t provided as an argument, the script uses the initial value “temp” and copies the file to the “temp” directory.
Conclusion
In conclusion, optional arguments are easy to incorporate in a Bash script once you are familiar with positional parameters or the getopts command. I believe after reading this article you shouldn’t face any difficulties in parsing and accessing optional arguments in Bash script.
People Also Ask
How to write a Bash script that takes optional arguments?
To write a Bash script that takes optional arguments, use positional parameters with default value. For instance, ${1:-default_value1}
syntax sets “default_value1” as the default value of the first positional parameter $1. If $1 is unset or null, it defaults to “default_value1”. Here is an example:
#!/bin/bash
# Set default values for optional arguments
arg1=${1:-default_value1}
arg2=${2:-default_value2}
# Access the arguments
echo "Argument 1: $arg1"
echo "Argument 2: $arg2"
Now you can call this script with or without providing arguments like below:
./script.sh # Uses default values
./script.sh value1 # Uses value1 for arg1, default_value2 for arg2
./script.sh value1 value2
What is the difference between required and optional arguments in Bash?
In Bash scripting, the difference between required and optional arguments lies in how they are treated by the script and the user’s interaction with them. Key differences between required and optional arguments are:
- Required arguments are parameters that must be provided by the user when invoking the script. Whereas optional arguments are parameters that users may choose to provide, but they are not mandatory.
- If required arguments are not provided, the script may fail or produce unexpected behavior. On the other hand, missing optional argument doesn’t hamper the core functionality of a script.
How to make an argument optional in a Bash script?
To make an argument optional in a Bash script, you can set a default value for the argument. Otherwise, use getopts command to parse options with arguments. Arguments processed by getopts command are optional until the corresponding options are triggered.
How to parse an optional argument to a Bash function?
To parse an optional argument to a Bash function, set a default value for the argument inside the Bash function. Look at the greet function of the following script:
#!/bin/bash
# Define a function with an optional argument
greet() {
local name="${1:-Guest}" # Use the provided argument or default to "Guest"
echo "Hello, $name!"
}
# Call the function with and without arguments
echo "Calling the function with no arguments:"
greet
echo "Calling the function with an argument:"
greet "John"
Related Articles
- How to Check Number of Arguments in Bash? [3 Methods]
- How to Use First Argument in Bash Script [5 Cases]
- How to Get Argument in Bash? [4 Methods]
- How to Pass Arguments to Bash Script? [5 Methods]
- How to Pass Array as an Argument in Bash Function? [3 Ways]
- How to Set Default Argument in Bash [2 Methods]
- How to Use OPTARG in Bash [3 Practical Examples]
- How to Use “getopts” in Bash [Complete Guide]
- [Solved] “bash: Argument list too long” Error
<< Go Back to Argument in Bash Script | Bash Functions | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners