什么时候开始循环 while [ -n "$1" ]; 执行?

zab*_*bop 1 linux shell bash shell-script

我有一个带有 while 循环的 shell 脚本

while [ -n "$1" ]; do
Run Code Online (Sandbox Code Playgroud)

我知道这$1指的是紧跟在脚本名称之后的参数,即firstargument,当我执行./myscript.sh firstargument. 做-n什么的?

Kus*_*nda 6

-n是对非空字符串的测试。

如果"$1"展开为空字符串,则该特定测试失败并且循环将不会执行。

这是有可能的是,循环体包含一个shift到下一个位置参数转移到声明$1,并在循环中通过脚本变量的这样的循环,直到它找到一个空的参数或涉及到的列表的末尾论据。

test实用程序等效于[,但[要求最后一个参数是]

测试也可以写成

while test -n "$1"; do
Run Code Online (Sandbox Code Playgroud)

双方[test有可能内置到你的shell,也应该作为外部命令下像一个标准的路径/bin

您将能够在man test以及 shell 手册(因为它是一个内置实用程序)中阅读有关此测试和其他测试的更多信息。

-n测试也是标准测试之一,因此也列在实用程序的 POSIX 标准中test


如果这个循环应该遍历shell 脚本的所有参数,那么如果参数为空,它可能会失败:

$ sh -c 'while [ -n "$1" ]; do printf "arg: %s\n" "$1"; shift; done' sh 1 2 3 "" 4 5 6
arg: 1
arg: 2
arg: 3
Run Code Online (Sandbox Code Playgroud)

相反,它可能应该使用类似的东西

for arg do
    if [ -n "$arg" ]; then
        # do something with "$arg"
    fi
done
Run Code Online (Sandbox Code Playgroud)

...显然,这取决于脚本的作用。

  • ...并且 `while` 可能与循环内的 `shift` 耦合(这就是为什么会使用它而不是 `if`)。 (4认同)