在这种情况下,你必须包含参数的命令,你正在运行,而不仅仅是一个单一的字符串,你应该多变量不能 EVAL直接使用,因为它会在以下情况下会失败:
function echo_arguments() {
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Argument 3: $3"
echo "Argument 4: $4"
}
# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"
结果:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg
请注意,即使将“ Some arg”作为单个参数传递,也eval
应将其读取为两个。
相反,您可以只使用字符串作为命令本身:
# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {
"$@";
}
请注意eval
和的输出之间的区别eval_command
:
eval_command echo_arguments arg1 arg2 "Some arg"
结果:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:
$($cmd))
失败时此方法有效。总是说找不到命令。谢谢!