bash - $# 和 ${#@} 的区别

标签 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

最佳答案

每个手册页 ( 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.

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

关于bash - $# 和 ${#@} 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30469040/

相关文章:

javascript - 只显示 10 个字符的长字符串?

string - 使用批处理文件检查文件路径的长度。 #字符串长度

bash - 将前缀 key 发送到 tmux session

bash - 如何正确转义 Makefile 的数据?

c - 如果 'strlen()' 本身返回字符串的长度,为什么我们要使用 'printf()' 呢?

c++ - 为什么 strlen() 比手动循环检查空终止字符快大约 20 倍?

java - 如何使用 JTextArea 输入字符串的字符查找单词的平均值

regex - Linux命令替换标准输入中没有 '\n'的字符

bash - bash:如何将脚本名称分配给变量并从另一个脚本调用它

bash - 如何在除最后一行之外的每一行末尾添加逗号?