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:

if [ $# -ne 2 ]; then
    echo "Error: Exactly 2 arguments are required."
    exit 1
else
    echo "You provided two arguments."
fi
$ ./test.bash 1 1
You provided two arguments.

$ ./test.bash 1
Error: Exactly 2 arguments are required.

$#: 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:

if [ $# -eq 2 ]; then
    if [[ $1 =~ ^[0-9]+$ ]] && [[ $2 == "start" || $2 == "stop" ]]; then
        echo "Processing with numeric argument $1 and command $2."
    else
        echo "Error: Invalid argument content."
        exit 1
    fi
elif [ $# -eq 1 ] && [[ $1 == "status" ]]; then
    echo "Checking status."
else
    echo "Error: Invalid number or type of arguments."
    exit 1
fi
$ ./test.bash 123 start
Processing with numeric argument 123 and command start.

$ ./test.bash 123 proceed
Error: Invalid argument content.

$ ./test.bash status
Checking status.

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:

echo Script name: $0
echo "Total number of arguments:" $#
echo "Arguments are:" $@

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.

arg_count=0
for arg in "$@"; do
    let arg_count++
done

if [ $arg_count -ne 2 ]; then
    echo "Error: Exactly 2 arguments are required."
    exit 1
else
    echo "You provided two arguments."
fi
$ ./test.bash 1 1
You provided two arguments.

$ ./test.bash 1
Error: Exactly 2 arguments are required.

"$@": 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.

if [[ $# != 2 ]]; then
    echo "Error: Exactly 2 arguments are required."
    exit 1
else
    echo "You provided two arguments."
fi
$ ./test.bash 1 1
You provided two arguments.

$ ./test.bash 1
Error: Exactly 2 arguments are required.

[[ $# != 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
    2) echo "Proceeding with 2 arguments.";;
    *) echo "Error: Invalid number of arguments."; exit 1;;
esac
$ ./test.bash 1 2
Proceeding with 2 arguments.

$ ./test.bash 1
Error: Invalid number of arguments.

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:

case $# in
    2|3)
        echo "Proceeding with 2 or 3 arguments."
        # Additional validation can be performed here
        ;;
    1)
        case $1 in
            "start"|"stop"|"status")
                echo "Single command argument: $1"
                ;;
            *)
                echo "Error: Invalid single argument."
                exit 1
                ;;
        esac
        ;;
    *)
        echo "Error: Unsupported number of arguments."
        exit 1
        ;;
esac
$ ./test.bash 1 2
Proceeding with 2 or 3 arguments.

$ ./test.bash stop
Single command argument: stop

$ ./test.bash proceed
Error: Invalid single argument.

$ ./test.bash 1 2 3 4
Error: Unsupported number of arguments.

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() {
    if [ $# -lt 2 ] || [ $# -gt 3 ]; then
        echo "Error: The script requires 2 or 3 arguments."
        return 1
    fi

    if ! [[ $1 =~ ^[0-9]+$ ]]; then
        echo "Error: First argument must be a number."
        return 1
    fi

    # Additional validation logic can be added here
    return 0
}

# Main script execution
if validate_arguments "$@"; then
    echo "Arguments validated. Proceeding with execution."
else
    exit 1
fi
$ ./test.bash 1
Error: The script requires 2 or 3 arguments.

$ ./test.bash start stop
Error: First argument must be a number.
  • 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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.