Press "Enter" to skip to content

Bash – Check Number of Arguments Passed to a Script in Linux

In the Linux bash shell environment, check number of arguments passed to a script to validate the call to the shell script. Below is an example:

Bash – Check Number of Arguments Passed to a Shell Script in Linux

The following shell script accepts three arguments, which is mandatory. So before start processing, first, it is checking for the arguments passed to the script. If the arguments are less than 3 or greater than 3, then it will not execute and if the arguments passed are three then it will continue the processing.

arg_test.sh

#!/bin/bash

if (( $# < 3 ))
then
    printf "%b" "Error. Not enough arguments.\n" >&2
    printf "%b" "usage: arg_test.sh file1 op file2\n" >&2
    exit 1
elif (( $# > 3 ))
then
    printf "%b" "Error. Too many arguments.\n" >&2
    printf "%b" "usage: arg_test.sh a b c\n" >&2
    exit 2
else
    printf "%b" "Argument count correct. Continuing processing...\n"
fi

echo "Start here."

Test with 2 Arguments

$ ./arg_test.sh 1 2

Output

Error. Not enough arguments.
usage: arg_test.sh a b c

Test with 4 Arguments

$ ./arg_test.sh 1 2 3 4

Output

Error. Too many arguments.
usage: arg_test.sh a b c

Test with 3 Arguments

$ ./arg_test.sh 1 2 3

Output

Argument count correct. Continuing processing...
Start here.

See also: