如何在shell脚本中保留$ @中的双引号?

Ste*_*oss 11 shell

假设我有一个非常简单的shell脚本'foo':

  #!/bin/sh
  echo $@
Run Code Online (Sandbox Code Playgroud)

如果我像这样调用它:

  foo 1 2 3
Run Code Online (Sandbox Code Playgroud)

它愉快地打印:

  1 2 3
Run Code Online (Sandbox Code Playgroud)

但是,假设我的一个参数是双引号括起来并包含空格:

  foo 1 "this arg has whitespace" 3
Run Code Online (Sandbox Code Playgroud)

foo愉快地打印:

  1 this arg has whitespace 3
Run Code Online (Sandbox Code Playgroud)

双引号被剥夺了!我知道shell认为它帮我一个忙,但是...我想得到原始版本的论点,不受shell解释的影响.有没有办法这样做?

Rom*_*aka 8

首先,你可能想要引用版本$@,即"$@".要感受差异,请尝试在字符串中放置多个空格.

其次,引号是shell语法的元素 - 它对你不利.为了保护它们,你需要逃避它们.例子:

foo 1 "\"this arg has whitespace\"" 3

foo 1 '"this arg has whitespace"' 3
Run Code Online (Sandbox Code Playgroud)

  • 有关 `"$@"` 以及引号如何引用其中内容的更多信息:https://unix.stackexchange.com/a/41595/21401 (2认同)

Ale*_*sky 5

双引号 $@:

#!/bin/sh
for ARG in "$@"
do
    echo $ARG
done
Run Code Online (Sandbox Code Playgroud)

然后:

foo 1 "this arg has whitespace" 3
Run Code Online (Sandbox Code Playgroud)

会给你:

1
this arg has whitespace
3
Run Code Online (Sandbox Code Playgroud)


Mit*_*dra 5

我要做的就是用空格引用收到的所有参数,这可能对您的情况有帮助。

for x in "${@}" ; do
    # try to figure out if quoting was required for the $x
    if [[ "$x" != "${x%[[:space:]]*}" ]]; then
        x="\""$x"\""
    fi
    echo $x
    _args=$_args" "$x
done

echo "All Cmd Args are: $_args"
Run Code Online (Sandbox Code Playgroud)


Bur*_*rad 2

您需要引用引号:

foo 1 "\"this arg has whitespace\"" 3
Run Code Online (Sandbox Code Playgroud)

或者(更简单地)

foo 1 '"this arg has whitespace"' 3
Run Code Online (Sandbox Code Playgroud)

您需要用双引号引起来,以确保 shell 在解析单词参数时不会删除它们。