防止shell转义单引号

时间:2018-01-18 03:26:24

标签: bash sh

脚本:

#!/bin/sh -x
ARGS=""
CMD="./run_this_prog"
. . . 
ARGS="-first_args '-A select[val]' "
. . . 
$CMD $ARGS

我希望在运行此shell脚本时将命令行扩展为:

./run_this_prog -first_args '-A select[val]'

相反,shell会做什么(请注意在每个单引号之前添加的' \')

+ ARGS=
+ CMD='./run_this_prog'
+ ARGS='-first_args '\''-A select[val]'\'' '

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

./run_this_prog -first_args \'\-A select\[val\]\'

我试图转义单引号,如:

ARGS="-first_args \'-A select[val]\' "

但这导致(在每次反斜杠后添加' \#39;)

+ ARGS=
+ CMD='./run_this_prog'
+ ARGS='-first_args \'\''-A select[val]\'\'' '

我做了谷歌搜索,但无法找到任何相关内容。我在这里错过了什么? 我在rel6 centOS上使用sh-3.2。

1 个答案:

答案 0 :(得分:6)

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

替换:

/var/www

使用:

#!/bin/sh -x
...
ARGS="-first_args '-A select[val]' "
$CMD $ARGS

有关此问题的更详细讨论,请参阅:"I'm trying to put a command in a variable, but the complex cases always fail!"