Check Number of Arguments in Bash

Check number of arguments in Bash

1. Overview

In Bash scripting, it’s often necessary to verify the number of arguments passed to a script to ensure correct script execution. This is crucial in scenarios where the script’s behavior depends on user-provided inputs. In this article, we will see different ways to check number of arguments in bash.

2. Introduction to Problem Statement

Given Script: A Bash script test.sh that performs a specific task requiring two arguments.
Expected Output: The script should apply different validations logic and display an error message or usage instructions based on validations.
Our Goal: To explore different methods for checking the number of arguments in a Bash script.

3. Using the Special Variable $#

Most straightforward way to check the number of arguments is using the special variable $#, which holds the count of arguments passed to the script.

Here is an simple example:

$#: Returns the number of arguments passed.
-ne: Numeric comparison for ‘not equal’.

This script checks if 2 arguments are passed to the script.

Let’s take more complex example:

This script Checks for exactly 2 arguments with specific conditions or a single argument that must be "status" and it uses regex (^[0-9]+$) to check if the first argument is a number.

If we want to print all the arguments passed to script as well, then we can use another special variable #@.
Let’s see with the help of example:

4. Using a Loop to Count Arguments

While not commonly used for just counting, a loop can be used to iterate over arguments and perform more complex checks.

"$@": Special parameter that expands to the positional parameters, starting from one.
let arg_count++: Increments the counter for each argument.
if [ $arg_count -ne 2 ]: Checks if total number of arguments passed to script is not equal to 2.

This script iterates over all the agruments using for loop and calculates the arg_count. It further do similar validation as in first script.

5. Using Conditional Expression

Bash allows the use of conditional expressions for a more compact syntax, especially when combined with other conditions.

[[ $# != 2 ]]: Checks if the number of arguments is not equal to 2 using a conditional expression.

[[ ... ]]: This is a Bash conditional expression. It’s an advanced version of the traditional [ … ] (test command) used for condition testing in Bash.

The double square brackets [[ … ]] provide a more powerful and versatile way to perform tests and are preferred in modern Bash scripts due to their robustness and support for additional features like pattern matching and regular expressions.

6. Using Case Statement

For scripts requiring checks against multiple possible argument counts, a case statement can be used.

Here is simple example:

case $# in: Starts a case statement based on the number of arguments.It matches specific patterns (2) and executes corresponding actions.

Let’s take more complex example:

In layman’s terms, the script is like a gatekeeper. It checks how many tickets (arguments) you have when you try to enter (run the script). If you have 2 or 3 tickets, it lets you in. If you have just 1 ticket, it checks what kind of ticket it is (start, stop, or status). If it’s the right kind, it lets you in; if not, it tells you it’s the wrong ticket. And if you have any other number of tickets, it just says that’s not allowed and doesn’t let you in.

7. Using Functions for Argument Validation

For scripts with complex argument handling, defining functions for argument validation can enhance readability and reusability.
Let’s create a custom function:

  • validate_arguments function checks the number of arguments and validates the first argument as a number using regex ^[0-9]+$.
  • if validate_arguments "$@"; then runs the validate_arguments function with all the arguments passed to script using special varialbe $@ and check if the outcome is successful.
  • The script execution proceeds only if the arguments pass all validations.

8. Conclusion

In Bash scripting, checking the number of arguments is essential for script reliability and correctness. The $# variable offers the most straightforward and efficient way to achieve this. However, other methods like loops, conditional expressions, and case statements provide additional flexibility and readability, especially in more complex scripts. The choice of method depends on the specific requirements of the script, such as the need for additional processing of arguments or handling multiple argument count scenarios.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *