When writing a bash script, it is a common task to check the input argument in bash to handle the arguments given by the user. If you try to execute the script without checking the input argument, you will get an error. So, keep reading this article to avoid these errors. Because, in this article, I will discuss 4 ways to check the input arguments in Bash.
What is an Input Argument in Bash?
An input argument is something you give to a bash script when it’s running from the command prompt. It’s a way for a user to control what your script does or what output it will generate.
When the script is executed in the terminal, the input arguments are typically supplied after the script name. For instance:
./my_script.sh arg1 arg2 arg3
In this example, arg1, arg2, and arg3 are input arguments. Bash scripts can access and process these arguments using positional parameters such as $1, $2, $3, etc. $1 represents the first argument, $2 the second, and so on.
4 Methods to Check If an Input Argument Exists in Bash
To check if an input argument exists, bash offers several operators like $#, -z, and -n. Additionally, a direct comparison with a Null string can be performed to accomplish this task.
In this part, I will give an overview of the 4 methods to check the existence of input arguments.
1. Check If an Input Argument Exists Using “$#” (Number of Arguments)
To make sure you have all your arguments, use $# a positional variable inside of if-else statement. This variable holds the number of arguments provided to your script. By evaluating its value, you can determine how many input arguments are present in the script. For instance, If $# returns 0, there are no arguments.
To check if no argument exists, you can use the syntax: “$#” -eq 0. Here’s an example:
#!/bin/bash
if [ "$#" -eq 0 ]; then
echo "No arguments provided."
else
echo "The number of arguments is: $#"
fi
Here if [ "$#" -eq 0 ]
returns true then the first echo statement will be printed. If not, the code will return “The number of arguments is:” followed by the argument number represented by $#.
As you can see from the image given above, the code returns “No arguments exist” as I did not pass any input argument. However, the code returns “Number of input arguments exist: 4”, upon providing four input arguments (hi how are you) after the ./special-var.sh
to the command line.
Check If At Least One Input Argument Exists
To check if at least one input argument exists, use $# -lt 1 instead of $# -eq 0 inside an if statement:
#!/bin/bash
if [ $# -lt 1 ]
then
echo "argument does not exist"
exit 1
else
echo "At least one argument exists"
fi
Here, the special variable $#
has the -lt
parameter. The -lt
parameter checks if there is at least one argument in bash. The script will output ‘Argument does not exist‘ if the users provide less than 1 argument. Otherwise, the script executes the else block.
As you see from the image, ./one-arg.sh read yellow green
command line returns “At least one argument exists” to the command line. Since the command contains three input arguments, the if [ $# -lt 1 ]
conditional statement returns false value and executes the else block.
Additionally, you can also modify the conditional statement if [ $# -lt 1 ]
to accomplish your desired task related to the input argument checking.
2. Check If an Input Argument Exists Using the “-n” Option
The -n option used with the if conditional statement checks whether the given argument is non-zero. If non-zero, it returns the expression of the if block. Otherwise, it executes the expression of the else block.
If you want to check whether an input argument exists using the -n option with array indexing, use the syntax: [ -n “${argument[0]}” ]. Here’s how:
#!/bin/bash
argument=("$@")
if [ -n "${argument[0]}" ]; then
echo "1st argument exists."
else
echo "1st argument does not exist."
fi
Here, $@
represents all the arguments provided by the users passed to the bash script and the indexed array type variable argument stores them in a contiguous manner. Following this, ${argument[0]}
stores the 1st element of the array which is nothing but the first argument. The -n
option inside the if condition checks whether the 1st argument in the array is non-empty. If it is empty, it returns the second expression otherwise it returns the former one.
After the execution of the script array.sh, the output will look something like this:
The above image states when no argument is passed after array.sh, the condition of theelse
block becomes true and prints “1st argument does not exist”. However, the execution of the same script followed by 2 arguments ar1 and ar2 makes the if
condition true and displays “1st argument exists”.
Check if the “N-th” Argument Exists in Bash
If you want to check whether the N-th argument exists in Bash, use the $N expression (N=1,2,3…n) with the -n option. For instance, “if [-n “$1″ ]” checks for the existence of an argument in the 1st position and so on.
Here’s a code snippet to check if an argument exists at the 2nd position using [ -n “$2” ]:
#!/bin/bash
if [ -n "$2" ]
then
echo "2nd argument '$2' passed"
else
echo "2nd argument missing"
fi
In the script, if the -n
option finds that the second argument referring to $2
is not zero, it executes ‘2nd argument passed’. Otherwise, it executes the else
block to print “2nd argument missing”.
The output after execution would be like this:
When you run the script n-arg.sh with one argument ar1
, it displays that 2nd argument is missing. Contrarily, when you pass 3 arguments (ar1 ar2 ar3), the script prints the message 2nd argument passed.
3. Check If an Input Argument is NULL Using the “-z” Option
The -z parameter checks whether the parameter is a NULL or empty string, and $1 represents the first parameter passed to the script.
Using the -z option with $1 , you can check if the first argument is NULL. Here’s the script shows how:
#!/bin/bash
if [ -z "$1" ]
then
echo "No arguments provided"
exit 1
else
echo "First argument '$1' provided"
fi
If no argument is provided while running this script, the if
the block is executed and it echoes code “No arguments provided”. However, when an argument is provided, the script will echo the else
block message.
Running it with no argument ./z-arg.sh
and with the argument hello
by ./z-arg.sh hello
gives the output as:
In this image, you can see when No arguments are provided after the above script, it echoes “No arguments provided”. When the hello
input argument is passed to the script, it displays the existence of the argument.
4. Check If an Input Argument Exists Using Direct Comparison
Alternatively, you can check if an input argument exists by directly comparing the argument with a NULL string:
#!/bin/bash
if [[ "$3" == ' ' ]] ; then
echo "3rd argument does not exist"
exit
else
echo "3rd argument exists"
fi
Here, $3
represents the third argument, and if[[ "$3" == ' ' ]]
is used to compare the third argument with the NULL string. If this condition is true, it means that the 3rd input argument does not exist. Otherwise, it means the 3rd argument exists.
Running it with two arguments ./null.sh red green
and with four arguments by ./null.sh red green yellow blue
gives the output as:
When you provide less than 3 arguments to the script, it won’t find the 3rd argument and print “3rd argument does not exist”. Else, it will show “3rd argument exists”.
Conclusion
In conclusion, these 3 methods provide you with a range of options for checking the existence of input arguments in Bash. Depending on your script’s requirements and your preferred coding style, you can choose the method that best suits your needs. By mastering these techniques, you’ll be well-equipped to create robust and reliable Bash scripts that handle user input with precision and finesse. Best wishes on your Bash scripting journey!
Frequently Asked Questions
How to check user input in Bash?
To check user input in Bash, use the read command to obtain user input and the -p option to display a prompt. Then, check if the input is empty using the -z option within an if statement.
Here’s an example:
read -p "Enter your input: " userInput
if [ -z "$userInput" ]; then
echo "Input is empty."
else
echo "User input is: $userInput"
fi
How to check the number of arguments in the shell?
To check the number of arguments in a shell script, use the special variable $#. The $# variable holds the count of arguments passed to the script. The following code snippet checks if there are arguments and displays the count if they exist or a message if none are provided.
if [ "$#" -eq 0 ]; then
echo "No arguments provided."
else
echo "Number of arguments: $#"
fi
How to pass 3 arguments in a shell script?
To pass three arguments to a shell script, simply provide them when running the script from the command line. Here’s how:
./your_script.sh arg1 arg2 arg3
Replace “your_script.sh” with the name of your shell script, and “arg1”, “arg2”, and “arg3” with the three arguments you want to pass.
For example, if your script is named “myscript.sh” and you want to pass three numbers as arguments:
./myscript.sh 10 20 30
Inside your script, you can access these arguments using the special variables $1, $2, and $3, where $1 corresponds to the first argument, $2 to the second, and so on.
Related Articles
- Check If a Variable Exists in Bash If Statement
- Check If a String Contains Substring, Number & Letter in Bash
- Check If a String is Empty or Not in Bash [5 Methods]
- How to Compare Strings in Bash With if Statement [6 Methods]
- How to Compare Numbers in Bash With If Statement [2 Methods]
- Check If Array Contains an Element in Bash [6 Methods]
- Bash if-else Condition in One-Line [2 Ways]
- Using grep in if Statement in Bash [4 Cases]
- How to Use Regex in Bash If Condition? [4 Cases]
- Bash rm If Exists [All Case Explained]
- What is ‘$?’ in the Bash if Statement? [8 Examples]
<< Go Back to If Else in Bash | Bash Conditional Statements | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners