How To Check Existence of Input Argument in a Bash Shell Script
There are three different ways:
Method 1: Using the “test” Command
The “test” command, also known as the “[” command, is a built-in command in Bash that tests for various conditions. One of the conditions that we can test using the “test” command is whether a variable exists or not. Here is an example code to check if an input argument exists using the “test” command:
if [ -z "$1" ]
then
echo "Input argument is missing."
exit 1
fi
echo "Input argument exists."
Here the “-z” option is used with the “test” command to check if the input argument is an empty string or not. The script will output an error message and exit with a status code of 1 if the input argument is an empty string. Otherwise, the script will continue executing, below I have provided and input argument for the code so it displays the message of existence of input of argument:
Method 2: Using the “$#” Variable
The “$#” variable stores the number of input arguments passed to a script. If the script expects at least one input argument, we can check if the “$#” variable is greater than zero. Here is an example code to check if at least one input argument exists using the “$#” variable:
if [ $# -eq 0 ]
then
echo "Input argument is missing."
exit 1
fi
echo "Input argument exists."
Here the “-eq” operator is used to check if the “$#” variable is equal to zero or not and if the “$#” variable is equal to zero, the script will display an error message and exit with a status code of 1. Otherwise, the script will continue executing, below I have provided and input argument for the code so it displays the message of existence of input of argument:
Method 3: Using the “-n” Option
The “-n” option is used to check if a variable is not empty. We can use this option to check if the input argument exists or not. Below I have given an example code that checks if an input argument exists using the “-n” option:
if [ -n "$1" ]
then
echo "Input argument exists."
else
echo "Input argument is missing."
exit 1
fi
Here, the “-n” option is used to check if the input argument is not empty and if the input argument is not empty, the script will display a success message. Otherwise, the script will display an error message and exit with a status code of 1, below I have provided and input argument for the code so it displays the message of existence of input of argument:
Conclusion
In shell scripting, checking the existence of input arguments is an essential step to ensure that the script runs as expected. We can use different techniques to check the existence of input arguments, such as using the “test” command, the “$#” variable, or the “-n” option. By implementing these techniques, we create more robust and reliable shell scripts that can handle input arguments.