Shell script -e 命令行参数无法识别

Shell script -e command line argument not recognized

无法识别在命令 bash 文件中使用 -e 作为标志。假设我们有一个名为 server.sh 的 bash 文件,它只回显所有传递的参数:

server.sh

echo "$@"

以下是 server.sh-e 作为第一个参数执行时的结果:

./server.sh -e hello ## output: hello
./server.sh -eeeee world ## output: world
./server.sh -eeeeeeeeeeeee what ## output: what

除以 -e 开头的参数外,任何其他参数均有效。谁能告诉我发生这种情况的原因?有没有办法让 -e 参数在 server.sh?

中被识别

这里有一个更简单的方法来重现您的问题:

$ echo "-e" "foo"
foo             # What happened to "-e"?

echo 将您的预期输出解析为选项是 POSIX 在可移植脚本中针对此命令发出警告的原因之一。

如果您尝试转储参数用于记录和调试目的,您可以使用 bash 的 printf %q:

 #!/bin/bash   
 # (does not work with sh)
 printf '%q ' "[=11=]" "$@"
 printf '\n'

这将转义输出参数,您可以将其复制粘贴回 shell 以便稍后重现(引用更改,但参数将相同):

$ ./myscript -e -avx --arg "my long arg" '(!#%^)(!*'
./myscript -e -avx --arg my\ long\ arg \(\!#%\^\)\(\!\*

如果你确实想以不明确的形式写出由空格分隔的参数,你可以使用:

#!/bin/sh
# works with bash and POSIX sh
printf '%s\n' "$*"

这导致:

$ ./myscript -e -avx --arg "my long arg" '(!#%^)(!*'
-e -avx --arg my long arg (!#%^)(!*