Passing Arguments to Bash Scripts
Passing arguments to Bash scripts is a straightforward process. You can provide arguments when you execute the script, and the script can then access and use those arguments.
Passing Arguments on the Command Line
To pass arguments to a Bash script, simply include them after the script name when you execute the script. For example, if you have a script named my_script.sh
, you can run it with arguments like this:
./my_script.sh arg1 arg2 arg3
In this example, the script can access the arguments arg1
, arg2
, and arg3
using the variables $1
, $2
, and $3
, respectively.
Accessing the Number of Arguments
In addition to accessing the individual arguments, you can also determine the total number of arguments passed to the script. This is done using the special variable $#
. For example:
echo "The script was called with $## arguments"
This will output the number of arguments passed to the script.
Handling Optional Arguments
Sometimes, you may want to make certain arguments optional in your Bash script. You can achieve this by checking the number of arguments using $#
and then providing default values or handling the missing arguments accordingly.
if [ "$#" -lt 2 ]; then
echo "Usage: $0 <arg1> <arg2> [arg3]"
exit 1
fi
arg1="$1"
arg2="$2"
arg3="${3:-default_value}"
In this example, the script checks if at least two arguments were provided. If not, it displays a usage message and exits. If the third argument is not provided, it sets a default value for arg3
.
By understanding how to pass and handle arguments in Bash scripts, you can create more flexible and powerful automation tools.