什么“$#”在bash中意味着什么?

时间:2014-04-11 18:49:34

标签: linux bash shell

我有一个脚本:

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

但我真的不知道$#在第三行意味着什么。

2 个答案:

答案 0 :(得分:8)

英镑符号很重要。

  1. 如果只是$#,那就是位置参数的数量,例如$1$2$3。 (请注意$0,请注意。)
  2. 如果是${#var},则是参数扩展中的字符数。 (字符串长度)
  3. 如果它是${#var[@]},则它是数组中元素的数量。由于bash数组是稀疏的,因此它可以与最后一个元素的索引加上不同

答案 1 :(得分:2)

这是传递的参数数量。

您可以阅读here,搜索“检测命令行参数”

相关问题