How to Check Number of Arguments in Bash? [3 Methods]

The special variable “$#” is used to check the total number of arguments provided in a Bash script. However, there are a couple of alternative methods to do that. In this article, I will discuss different ways to count the number of arguments passed to a script. Additionally, I will highlight the use of the total length of arguments in a Bash script for various purposes.

3 Methods to Check Total Number of Arguments in Bash Script

The “$#” variable is the default choice for counting the total number of arguments passed to a Bash script. Another variable “$@” holds all the arguments. Therefore, you can use the parameter expansion or a basic for loop with the “$@” variable to find the count of arguments of a Bash script. Check the detailed processes below:

1. Using “$#” Special Variable

In Bash, the “$#” variable contains the length of the arguments of a Bash script. To check the number of arguments of a script, use it as follows:

!/bin/bash
echo "Number of args: $#"

Getting the length of command line arguments in Bash scriptHere, three arguments 1, 2, and “a” are provided to the script arglen.sh. Within the script, the value of “$#” is 3 indicating the total number of arguments.

2. Using Expansion of Special Variable “$@”

The special variable “$@” contains all the arguments of a Bash script. When expanded, it returns an array of the command line arguments. Hence, the length of “$@” actually represents the number of arguments passed to a script. For example:

!/bin/bash
echo "Number of args: ${#@}"

Getting the number of arguments in Bash script using $@Here, “a”, “b”, “c” and “d” are arguments provided to the script. And, ${#@} retrieves that there are 4 arguments parsed to the script.

3. Iterating Over “$@” With a For Loop

You can also employ a for loop to count the number of arguments stored in the “$@” variable. To count the number of arguments of a Bash script in this way first initiate a counter variable. Then for each command line argument increase the value of the counter. Eventually, the counter will contain the number of arguments of the script. Check the script below for the practical demonstration:

#!/bin/bash

c=0
for arg in "$@"; do
  echo "$arg"
  ((c++))
done
echo "Number of args: $c"
EXPLANATION

In this script, the for loop iterates over each command-line argument stored in the $@ variable. With each iteration, the argument is printed and the counter c is incremented by c++. Finally, the script outputs the total number of arguments by echoing $c.

Getting number of arguments in Bash script using a for loop

From the above image, 1, “a 2” and “b 3” are three command line arguments provided to the arglen2.sh script. By iterating over “$@”, the program counts that the number of arguments of the script is 3.

How to Access Bash Script Arguments Using Arguments Length?

Using the length of command line arguments, one can access all the arguments passed to a script. The idea is to create a variable that holds the number of arguments ($#). Then a while loop can be used to access each argument using the BASH_ARGV array. Here’s an example demonstrating this approach:

#!/bin/bash

c=$(($#-1))
i=1
while [ $c -ge 0 ];
do
  echo "$i-th Argument: ${BASH_ARGV[$c]}"
  c=$((c-1))
  i=$((i+1))
done
EXPLANATION

The Bash script initiates two variables c and i. It sets the value of c to the total number of arguments passed to the script subtracting by 1. And, the value of the variable i is set to 1.

Then the while loop continues as long as the value of c is greater than or equal to 0. On each iteration of the while loop, $i provides the index of the argument and ${BASH_ARGV[$c] provides the argument itself. Finally, counter c is decremented by 1 while the value of i is incremented by 1.

Accessing each command line argument using number of argumentsThere are four arguments provided to the script. They are a, 4, b, and 51. Once executed the script prints the arguments with their index. For instance, it shows that b is the 3rd argument of the script.

How to Check if Any Input Argument Provided in Bash Script?

In a Bash script, one can check if any argument is provided to it. To do that, compare the number of arguments ($#) with 0. The value of $# being 0 means no command-line arguments are provided. Otherwise, there exist one or more arguments. For instance:

#!/bin/bash

if [ $# -eq 0 ]; then
  echo "No Argument Provided."
else
  echo "Arguments Provided"
fi
EXPLANATION

The Bash script compares whether the number of command line arguments is 0 using the -eq operator. If so it echos “No Argument Provided.”. Otherwise, it prints a message that “Arguments Provided”.

Checking if there is any input argument in Bash script

When the script is executed without any argument it shows “No Argument Provided”. On the other hand, executing the script with arguments “a” and “b” displays “Arguments Provided”.

How to Check Whether Required Arguments Are Provided in Bash Script?

A Bash script may require a fixed number of mandatory arguments. Executing such scripts without the necessary arguments results in an error. In such situations, it is a smart way to check whether the user provided the required number of necessary arguments before executing the main part of the script. For instance, a bash script for summing up numbers may take multiple arguments, but at least two arguments must be provided. This can be handled by comparing “$#” variable with 2:

#!/bin/bash

if [ $# -lt 2 ]; then
  echo "Provide at least two arguments to proceed."
  exit 1
fi

sum=0
for arg in "$@"; do
  sum=$((sum + arg))
done
echo "Sum of the arguments: $sum"
EXPLANATION

The if block of the bash script compares whether the number of arguments is less than two. If so the program exits echoing a message instructing the user to provide at least two arguments.

If two or more arguments are provided, the script calculates the sum of all the arguments passed and displays the result. First, it initiates a variable named sum and sets its value to 0. Then it iterates over the command-line arguments and accumulates them in the sum variable. Finally, it outputs the total sum of the arguments.

Checking if required number of arguments provided in Bash script

When only one argument 7 is given the script halts its execution. On the contrary, when three arguments 7, 13, and 11 are provided it gives the summation of the arguments which is 31.

How to Check Existence of N-th Argument in Bash Script?

Sometimes it is necessary to check the existence of an argument located at a specific position. For example, it may be required to check whether a particular argument such as the second one exists or not. To check the existence of a particular argument in a script, use the code below:

#!/bin/bash

if [ -n "$2" ]; then
  echo "2nd argument exists."
elif [ -z "$2" ] && [ $# -gt 2 ]; then
  echo "2nd argument exists but it's an empty string."
else
  echo "2nd argument missing."
fi
EXPLANATION

The script first checks the length of the second argument($2) using -n within the if statement.

If true, the nonzero length indicates that the second argument exists.

Then, the program proceeds to an elif condition. In the elif statement, it evaluates two conditions. Whether the number of arguments passed to the script is greater than two and the second argument is an empty string. If both conditions are met, it indicates that the second argument exists but is empty.

Lastly, if none of the previous conditions are satisfied, it concludes that the second argument is missing.

Checking the existence of a particular command line argument

In the first execution, the second argument “c” is provided after the first argument 7. So the script shows that the second argument exists. However, in the later execution, "" is provided as the second argument. Hence, the program shows that the second exists but it’s an empty string. Finally, when the script is run without providing any second argument it displays that the second argument is missing.

Conclusion

In conclusion, the number of command line arguments has some important usage in Bash scripting. Fortunately, there are at least three ways to get the count of common line arguments. Among them, “$#” is the go-to choice to find the number of arguments. Other approaches also work and can be super useful in specific situations.

People Also Ask

What is the maximum length of an argument in Bash?

The maximum length of an argument in Bash must not exceed MAX_ARG_STRLEN (a system-defined value), typically set to 131072 bytes. You can determine the system’s maximum argument length using the getconf command with ARG_MAX. This command provides the maximum length of the arguments that can be passed to a process:

getconf ARG_MAX

How to get the length of the first argument?

To get the length of the first argument in a Bash script, you can use the ${#1} syntax. Here’s an example:

#!/bin/bash
echo "Length of the first argument: ${#1}"

What will be the value of $# if shifted by one?

If you use the shift command in a Bash script, the value of $# will decrease by one. For instance, if you have three positional parameters initially and you execute shift once, the value of $# will decrease from 3 to 2.

How can I get the length of all arguments given to a function in bash?

You can get the length of all arguments given to a function in Bash by using the $# variable within the function. For instance, if you call a function with three arguments then the value of the variable $# within the function will be three.

Related Articles


<< Go Back to Argument in Bash Script | Bash Functions | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

2 thoughts on “How to Check Number of Arguments in Bash? [3 Methods]”

  1. Your BASH_ARGV method seems to be working reliably only if you have activated the “extdebug” option BEFORE, AND if your script has NOT been invoked by another script. This should at least be mentioned!
    Unfortunately none ot the methods can reliably be used within a script WITHOUT arguments invoked by “source” or “.” because in this case they may be reporting the same non-zero “$#” possibly present OUTSIDE the script BEFORE sourcing it (e. g. from a higher level script or from the “set” command). Do you know a solution for this particular case?

    Reply
    • Invoking a script by another script is not the usual scenario. You are right that if the script is invoked by another script BASH_ARGV method won’t work as expected (This should be mentioned for sure). For “extdebug”, you may have to turn on extended debugging to access arguments using BASH_ARGV but it works for me in bash 5.1.16(1) without turning “extdebug” on.

      You can definitely reliably use the methods mentioned in the article to check the number of arguments of a single script no matter WITH or WITHOUT arguments. If there is no argument, It won’t return non-zero “$#” while invoking the script by “source” or “.”.

      However, probably you are getting confused about the number of arguments while sourcing a script from another script. It can look like this:

      script1.sh

      #!/bin/bash

      echo "number of arguments: $#" # output : 0

      source ./same_process1.sh a b c

      echo "number of arguments: $#" # output : 3

      script2.sh

      #!/bin/bash

      echo "number of arguments: $#" # output : 0

      Here, script2.sh is invoked with three arguments within script1.sh. Now, if script1.sh is invoked WITHOUT arguments, “$#” will return 0 before calling the second script and return 3 after the invocation of the second script.

      At this point, you can save the argument list of the script2.sh and reset the positional parameters to get the actual number of the arguments of script1.sh.

      script1.sh

      #!/bin/bash

      # output : 0

      echo "number of arguments: $#"

      source ./same_process1.sh a b c

      # output : 3

      saved_argv=("$@")

      # Reset positional parameters for the script

      set --

      echo "number of arguments: $#"

      To know more about how to call another script in Bash read this guide.

      Reply

Leave a Comment