$#和$ {#@}之间的区别

时间:2015-05-26 21:15:45

标签: bash string-length

我正在查看以下代码,发现$#和$ {#@}都打印相同的值。有人能告诉我两者之间有什么区别吗?

# length.sh

E_NO_ARGS=65

if [ $# -eq 0 ]  # Must have command-line args to demo script.
then
  echo "Please invoke this script with one or more command-line arguments."
  exit $E_NO_ARGS
fi  

var01=abcdEFGH28ij
echo "var01 = ${var01}"
echo "Length of var01 = ${#var01}"
# Now, let's try embedding a space.
var02="abcd EFGH28ij"
echo "var02 = ${var02}"
echo "Length of var02 = ${#var02}"

echo "Number of command-line arguments passed to script = ${#@}"
echo "Number of command-line arguments passed to script = $#"

exit 0

1 个答案:

答案 0 :(得分:8)

每个手册页(3.5.3 Shell Parameter Expansion):

  

${#parameter}

     

参数长度。参数值的字符长度被替换。 如果参数为* @ ,则替换值为位置参数的数量。如果参数是*或@下标的数组名称,替换值是数组中元素的数量。

所以${#@}只是一个特例,因为$#是表达位置参数数量的常用方法。