Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "$#" mean in bash? [duplicate]

Tags:

linux

bash

shell

I have a script with this:

login {
    # checking parameters -> if not ok print error and exit script
    if [ $# -lt 2 ] || [ $1 == '' ] || [ $2 == '' ]; then
        echo "Please check the needed options (username and password)"
        echo ""
        echo "For further Information see Section 13"
        echo ""
        echo "Press any key to exit"
        read
        exit
    fi

  } # /login

But I really dont know what the $# means on the third line.

like image 289
dominique120 Avatar asked Apr 11 '14 18:04

dominique120


2 Answers

The pound sign counts things.

  1. If it's just $#, it's the number of positional parameters, like $1, $2, $3. (Not counting $0, mind you.)
  2. If it's ${#var}, it's the number of characters in the expansion of the parameter. (String length)
  3. If it's ${#var[@]}, it's the number of elements in the array. Since bash arrays are sparse, this can be different from the index of the last element plus one.
like image 113
kojiro Avatar answered Nov 01 '22 21:11

kojiro


It's the number of arguments passed.

You can read it here, search for "Detecting command line arguments"

like image 34
Andreas Wederbrand Avatar answered Nov 01 '22 23:11

Andreas Wederbrand