如果是什么意思呢?

我是Unix / Linux的新手。 我正试图在我面前了解开发人员的代码。 有人可以告诉我, if [ $# -lt 2 ]是什么意思吗?

在Bash中, $#扩展为已设置的位置参数的数量。

if [ $a -lt $b ]表示if [ $a -lt $b ]的值是否小于b的值。

if [ $# -lt 2 ]表示设置的位置参数数量是否小于2。

在一个工作示例中,您可能会使用它来计算给函数的参数。 如果将函数定义为:

 count_words(){ if [ $# -lt 2 ] then echo "There are less than two words." else echo "There are 2 or more words." fi } 

然后用不同数量的单词调用函数,结果如下:

 $ count_words hello There are less than two words. $ count_words how many words There are two or more words. $ count_words There are less than two words. $ count_words two words There are two or more words. 

这是三件事的组合:

  • $#是一个shell变量,它包含脚本或函数的位置参数数。

  • [不是特殊的语法,而是程序的名称 – 它是test的别名。 (看看man [man test 。)

    [的命令行被解析为表达式: [ $# -lt 2 ]调用[带参数$#-lt2] (这只是一个可视分隔符)。 它返回一个成功的退出代码,设置$? 如果表达式求值为true(即,如果脚本的参数数小于2)或者失败的退出代码, $? ,设置$?1 。 您可以输入以下内容来查看:

     [ 1 -lt 2 ]; echo $? # 1 < 2 is true: 0 [ 2 -lt 1 ]; echo $? # 2 < 1 is false: 1 
  • if condition; then body; fi if condition; then body; fi评估命令condition ,如果它返回成功的退出代码,则继续评估body的命令。

值得注意的是你可能会遇到的一些事情:

  • true实用程序始终返回成功的退出代码, false始终返回失败,因此您可以在条件中使用它们,例如:

     while true; do … done 
  • if [ $foo = "yes" ] $foo扩展为空字符串( [ = yes ] ),或者包含空格的字符串( [ no thanks = yes ] ), if [ $foo = "yes" ]将无效。 所以你经常会看到:

     if [ "x$foo" = "xyes" ] 

    所以[收到一个参数xno thanks作为=的第一个操作数。

  • [[ ... ]]是一个shell 关键字 (不是内置的 ),具有特殊的解析规则来解决上述限制,并且可以提供其他function。