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

后端 未结 5 1823
暖寄归人
暖寄归人 2020-12-04 08:31

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


        
相关标签:
5条回答
  • 2020-12-04 08:50

    Below is the easy one -

    cat countvariable.sh

    echo "$@" |awk '{for(i=0;i<=NF;i++); print i-1 }'
    

    Output :

    #./countvariable.sh 1 2 3 4 5 6
    6
    #./countvariable.sh 1 2 3 4 5 6 apple orange
    8
    
    0 讨论(0)
  • 2020-12-04 08:56

    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."

    0 讨论(0)
  • 2020-12-04 08:56

    that value is contained in the variable $#

    0 讨论(0)
  • 2020-12-04 09:03

    The number of arguments is $#

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

    0 讨论(0)
  • 2020-12-04 09:06
    #!/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"
    
    0 讨论(0)
提交回复
热议问题