if [ $# -lt 2 ] 是什么意思?

Adi*_*678 7 scripts

我是 Unix/Linux 的新手。我试图了解我之前的开发人员的代码。谁能告诉我这条线if [ $# -lt 2 ]是什么意思?

Arr*_*cal 15

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

if [ $a -lt $b ] 表示如果 a 的值小于 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
}
Run Code Online (Sandbox Code Playgroud)

然后调用不同字数的函数,结果如下:

$ 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.
Run Code Online (Sandbox Code Playgroud)