如何使用参数扩展存储在 sh 变量中的命令?

How to extend command stored in sh variable with parameters?

我尝试 google 这个问题并尝试了不同的方法,但我未能真正执行命令:/ 我想在一组条件检查中构造一个命令。这是我想要实现的目标:

run_script=`command`

if type command &>/dev/null; then
    run_script=`command`
else
    run_script=`something command`
fi

# while ... do
    $params=`-a -b -c` # calculated
    $anotherparam = "./test.file" # calculated

    # run $run_script+$params+$anotherparam ???
    # like we run "command -a -b -c ./test.file" command
# done

注:仅为示例

如何进行这种组合?我不能使用数组,因为我需要它与 sh

兼容

这会引起强烈的意见。

如果您完全确定您只会收到可信的、非恶意的输入,eval 是标准 shell 的一部分,是完成此任务的完美工具。

参见:https://unix.stackexchange.com/questions/278427/why-and-when-should-eval-use-be-avoided-in-shell-scripts

The arguments are concatenated together into a single command, which is then read and executed, and its exit status returned as the exit status of eval. If there are no arguments or only empty arguments, the return status is zero.

if type command &>/dev/null; then
    run_script="command"
else
    run_script="something command"
fi

params="-a -b -c" # calculated
anotherparam="./test.file" # calculated

eval "$run_script $params $anotherparam"

您可以使用:

if type -p command; then
    run_script="command"
else
    run_script="something command"
fi

params="-a -b -c"
anotherparam="./test.file"

"$run_script" $params $anotherparam

OP 代码的更改:

  • 使用type -p cmd代替type cmd &>/dev/null
  • run_script="command"
  • 使用引号而不是反引号
  • 去掉等号两边的空格=
  • 去掉等号左边的$

更正POSIX sh动态构造带参数命令调用的方式:

#!/bin/sh

run_script='command'

if command -v "$run_script" >/dev/null 2>&1; then
    set -- "$run_script"
else
    set -- "something" "$run_script"
fi

# while ... do
#    $params=`-a -b -c` # calculated
    set -- "$@" -a -b -c # calculated
#    $anotherparam = "./test.file" # calculated
    set -- "$@" "./test.file" # calculated
    # run $run_script+$params+$anotherparam ???
    "$@" # run command with its parameters
    # like we run "command -a -b -c ./test.file" command
# done

解释:

  • if command -v "$run_script" >/dev/null 2>&1:测试"$run_script"命令是否存在。
  • set -- "$run_script":将参数数组设置为 "$run_script" 命令。
  • set -- "something" "$run_script":将参数数组设置为第一个参数为 "$run_script".
  • something 命令
  • set -- "$@" -a -b -c:设置参数数组,其中 "$@" 参数数组的当前内容,以及 -a-b-c 作为附加参数。
  • 独立"$@":调用参数数组中包含的命令和参数。