Bash script – How to check number of supplied command-line arguments

The total number of supplied command-line arguments is hold by a in bash’s internal variable $#. Consider a following example of simple bash script which will print out a total number of supplied command-line arguments to the STDOUT:

#!/bin/bash
echo $#

Save the above into a file called eg. arguments.sh and execute:

$ bash arguments.sh 1 2 3 4
4

From the above we can see that four arguments separated by space have been supplied to our script namely 1 2 3 4. During the script’s execution a content of the internal variable $# had been printed out.

When writing a script you sometime need to force users to supply a correct number of arguments to your script. Using the above mentioned internal variable $# and if statement this can be achieved as shown below:

#!/bin/bash
if [ "$#" -ne 2 ]; then
    echo "You must enter exactly 2 command line arguments"
fi
echo $#

The above script will exit if the number of argument is not equal to 2.

$ bash arguments.sh 1 
You must enter exactly 2 arguments
$ bash arguments.sh 1 2 3 4
You must enter exactly 2 arguments
$ bash arguments.sh 1 2
2


Comments and Discussions
Linux Forum