$# 和 ${#@} 的区别
Difference between $# and ${#@}
我正在查看以下代码,发现 $# 和 ${#@} 打印的值相同。谁能告诉我这两者有什么区别?
# 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
每个手册页 (3.5.3 Shell Parameter Expansion):
${#parameter}
Parameter length. The length in characters of the value of parameter is substituted. If parameter is *
or @
, the value substituted is the number of positional parameters. If parameter is an array name subscripted by * or @, the value substituted is the number of elements in the array.
所以 ${#@}
只是一个特例,因为 $#
是表示位置参数数量的常用方式。
我正在查看以下代码,发现 $# 和 ${#@} 打印的值相同。谁能告诉我这两者有什么区别?
# 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
每个手册页 (3.5.3 Shell Parameter Expansion):
${#parameter}
Parameter length. The length in characters of the value of parameter is substituted. If parameter is
*
or@
, the value substituted is the number of positional parameters. If parameter is an array name subscripted by * or @, the value substituted is the number of elements in the array.
所以 ${#@}
只是一个特例,因为 $#
是表示位置参数数量的常用方式。