为 bash exec 构建命令

为 bash exec 构建命令

我有一个 shell 脚本,它运行后exec会用另一个命令替换自身。另一个命令带有一些可选参数。

exec mycommand $ARG1 $ARG2 $ARG3

这些参数中的任何一个都可以填充或不填充。如果未填充,则它们不会呈现为函数的参数。例如:

# if you have:
ARG1=foo
ARG3=bar
exec mycommand $ARG1 $ARG2 $ARG3
# then you get:
exec mycommand foo bar

但是,我希望这些参数的值中的空格是合法的,并且这不会导致它们产生额外的参数。也就是说,

# if you have
ARG1="foo bar baz"
ARG2="qux"
exec mycommand $ARG1 $ARG2 $ARG3
# then I want:
exec mycommand "foo bar baz" qux
# not:
exec mycommand foo bar baz qux

我尝试将转义的引号放入参数中,但 exec 希望它们实际上是值的一部分。

ARG1="\"foo bar baz\""
exec mycommand $ARG1 $ARG2 $ARG3
# gives you:
exec mycommand \"foo bar baz\"

我也尝试在 exec 中引用变量,但是当没有参数时它就开始传递空字符串:

ARG2="foo bar"
exec mycommand "$ARG1" "$ARG2" "$ARG3"
# gives you:
exec mycommand "" "foo bar" ""

有没有更好的方法来构造命令并将其传递给 exec? 有没有其他方法可以用另一个进程替换当前进程?

答案1

使用 bash 时,可以使用数组,并且所有变量都必须正确引用:

ARG1="foo bar baz"
ARG3="qux"

cmd=( mycmd )

[[ -n "$ARG1" ]] && cmd+=( "$ARG1" )
[[ -n "$ARG2" ]] && cmd+=( "$ARG2" )
[[ -n "$ARG3" ]] && cmd+=( "$ARG3" )

printf "%s\n" "${cmd[@]}"
#exec "${cmd[@]}"

这将为您提供所需的调用:exec mycommand "foo bar baz" qux 没有“空字符串”参数。如果您对它的运行方式感到满意,请删除 printf 行并取消注释 exec 行。

相关内容