【问题标题】:What does the "$#" special parameter mean in Bash?Bash 中的“$#”特殊参数是什么意思?
【发布时间】:2013-12-13 19:48:02
【问题描述】:

我遇到过代码

if [ $# -eq 1  ]; then
   echo "usage: Phar ~/flashmem ~/archive"
   exit
fi

我以前从未遇到过[ $# -eq 1 ];,我似乎无法找到意义。它有什么作用?

【问题讨论】:

  • 不幸的是,bash manual 的编写方式使得很难找到像$# 这样的东西,因为它没有显示$$*$@$#等所谓的“特殊参数”在section 3.4.2, Special Parameters中。
  • Google 比 man(1)bash 更积极地去除符号也无济于事。
  • @KeithThompson:使用 Bash 手册的"entirely on one web page" 版本,$# 的第一个发现显示了所需的位置。 ;)
  • @MichaelBrux:查看 git 历史记录,该更改(在描述前添加 ($#))是在 2014 年 10 月 9 日在 bash-20140926 快照(提交 30595b57d9)中进行的。更改出现在 4.3 版中。不幸的是,git 历史并没有显示做了什么更改,只显示了日期快照的名称。

标签: bash shell if-statement parameters


【解决方案1】:

$# 返回作为参数传递的参数的数量。

#!/bin/bash
echo $#

现在

./testess.sh test1 test2 test3

这将返回3

./testess.sh test1 test2 test3 test4 test5

这将返回5

所以在您的代码中,如果$# 等于第一个(只传递了一个参数),则执行echo 命令。

【讨论】:

    【解决方案2】:

    Expands to the number of positional parameters in decimal.

    (复制自man bash,在Special Parameters 下)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 2022-12-16
      • 2016-05-24
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多