Bash 在不扩展转义空格的情况下将字符串作为命令执行
Bash execute string as command without expanding escaped spaces
我有一个外部可执行文件需要传递参数。使用 bash 脚本,我有确定这些参数的代码。一些参数可能已经转义了空格。
然后我需要执行该字符串,而不扩展每个参数。
# ... some code that determines argument string
# the following is an example of the string
ARGSTR='./executable test\ file.txt arg2=true'
exec ${ARGSTR}
我必须扩展 $ARGSTR
以便我可以将参数传递给 ./executable
,但不应扩展每个参数。我试过引用 "test file.txt"
,但这仍然没有将它作为一个参数传递给 ./executable
。
有没有办法做这样的事情?
我们使用数组而不是字符串:
#!/usr/bin/env bash
ARGSTR=('./executable' 'test file.txt' 'arg2=true')
exec "${ARGSTR[@]}"
参见:
BashFAQ-50 - 我正在尝试将命令放入变量中,但复杂的情况总是失败。
这可能会达到你想要的效果:
ARGSTR='./executable test\ file.txt arg2=true'
exec bash -c "exec ${ARGSTR}"
我有一个外部可执行文件需要传递参数。使用 bash 脚本,我有确定这些参数的代码。一些参数可能已经转义了空格。 然后我需要执行该字符串,而不扩展每个参数。
# ... some code that determines argument string
# the following is an example of the string
ARGSTR='./executable test\ file.txt arg2=true'
exec ${ARGSTR}
我必须扩展 $ARGSTR
以便我可以将参数传递给 ./executable
,但不应扩展每个参数。我试过引用 "test file.txt"
,但这仍然没有将它作为一个参数传递给 ./executable
。
有没有办法做这样的事情?
我们使用数组而不是字符串:
#!/usr/bin/env bash
ARGSTR=('./executable' 'test file.txt' 'arg2=true')
exec "${ARGSTR[@]}"
参见:
BashFAQ-50 - 我正在尝试将命令放入变量中,但复杂的情况总是失败。
这可能会达到你想要的效果:
ARGSTR='./executable test\ file.txt arg2=true'
exec bash -c "exec ${ARGSTR}"