How do I find the number of arguments passed to a Bash script?

BashArguments

Bash Problem Overview


How do I find the number of arguments passed to a Bash script?

This is what I have currently:

#!/bin/bash
i=0
for var in "$@"
do
  i=i+1
done

Are there other (better) ways of doing this?

Bash Solutions


Solution 1 - Bash

The number of arguments is $#

Search for it on this page to learn more: http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

Solution 2 - Bash

#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
    echo "The length of argument '$var' is: ${#var}"
    (( count++ ))
    (( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"

Solution 3 - Bash

to add the original reference:

You can get the number of arguments from the special parameter $#. Value of 0 means "no arguments". $# is read-only.

When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.

see Bash Reference Manual in section 3.4.2 Special Parameters:

  • "The shell treats several parameters specially. These parameters may only be referenced"

  • and in this section for keyword $# "Expands to the number of positional parameters in decimal."

Solution 4 - Bash

Below is the easy one -

cat countvariable.sh

echo "$@" | awk '{print NF}'

Output :

#./countvariable.sh 1 2 3 4 5 6
6
#./countvariable.sh 1 2 3 4 5 6 apple orange
8

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsabriView Question on Stackoverflow
Solution 1 - BashzsalzbankView Answer on Stackoverflow
Solution 2 - BashDennis WilliamsonView Answer on Stackoverflow
Solution 3 - BashMichael BruxView Answer on Stackoverflow
Solution 4 - BashVIPIN KUMARView Answer on Stackoverflow