什么 while(($#)); 做 ...; 转移; done 在 bash 中是什么意思,为什么有人会使用它?

njk*_*015 4 parameters bash while-loop

我在网上的 bash 脚本教程中遇到了以下 while 循环:

while(($#)) ; do
   #...
   shift
done
Run Code Online (Sandbox Code Playgroud)

我不明白在 while 循环中使用位置参数基数。我知道该shift命令的作用,但是 while 语句与shift?

Ben*_* W. 5

每次执行时shift,位置参数的数量都会减少一:

$ set -- 1 2 3
$ echo $#
3
$ shift
$ echo $#
2
Run Code Online (Sandbox Code Playgroud)

所以这个循环会一直执行,直到每个位置参数都被处理完;(($#))如果至少有一个位置参数,则为真。

这样做的一个用例是(复杂的)选项解析,其中您可能有带有参数的选项(想想):选项的参数将被处理并通过附加的.command -f filenameshift

有关复杂选项解析的示例,请参阅BashFAQ/035ComplexOptionParsing。第二个链接的最后一个示例Rearrangeing arguments使用了精确的while (($#))技术。


jm6*_*666 5

让我们有一个脚本shi.sh

while(($#)) ; do
    echo "The 1st arg is: ==$1=="
    shift
done
Run Code Online (Sandbox Code Playgroud)

运行它:

bash shi.sh 1 2 3  #or chmod 755 shi.sh ; ./shi.sh 1 2 3
Run Code Online (Sandbox Code Playgroud)

你会得到

The 1st arg is: ==1==
The 1st arg is: ==2==
The 1st arg is: ==3==
Run Code Online (Sandbox Code Playgroud)

请注意:第一(以及 的用法$1)。