防止shell转义单引号

Sha*_*dyy 3 bash sh

脚本:

#!/bin/sh -x
ARGS=""
CMD="./run_this_prog"
. . . 
ARGS="-first_args '-A select[val]' "
. . . 
$CMD $ARGS
Run Code Online (Sandbox Code Playgroud)

我想在运行这个shell脚本时像这样扩展命令行:

./run_this_prog -first_args '-A select[val]'
Run Code Online (Sandbox Code Playgroud)

而不是shell做什么(注意在每个单引号之前添加'\'):

+ ARGS=
+ CMD='./run_this_prog'
+ ARGS='-first_args '\''-A select[val]'\'' '
Run Code Online (Sandbox Code Playgroud)

以及它在命令行上运行的内容(转义每个特殊字符 - 不是我想要的):

./run_this_prog -first_args \'\-A select\[val\]\'
Run Code Online (Sandbox Code Playgroud)

我试图逃避单引号,如:

ARGS="-first_args \'-A select[val]\' "
Run Code Online (Sandbox Code Playgroud)

但结果是(在每次反斜杠后添加'\'):

+ ARGS=
+ CMD='./run_this_prog'
+ ARGS='-first_args \'\''-A select[val]\'\'' '
Run Code Online (Sandbox Code Playgroud)

我做了我的谷歌搜索,但找不到任何相关的东西.我在这里错过了什么?我在rel6 centOS上使用sh-3.2.

Joh*_*024 6

一旦引号出现在字符串中,它就不会按照你想要的方式工作:字符串引号不是语法元素,它们只是文字字符.这是bash提供数组的一个原因.

更换:

#!/bin/sh -x
...
ARGS="-first_args '-A select[val]' "
$CMD $ARGS
Run Code Online (Sandbox Code Playgroud)

附:

#!/bin/bash -x
...
ARGS=(-first_args '-A select[val]')
"$CMD" "${ARGS[@]}"
Run Code Online (Sandbox Code Playgroud)

有关此问题的更详细讨论,请参阅:"我正在尝试将命令放在变量中,但复杂的情况总是失败!"