发出带有由条件决定的选项的命令

Jef*_*ski 2 bash options shell-script

我正在尝试制作一个 shell 脚本,它会向用户提出一些问题,并将根据用户的选择发出带有某些或其他选项的最终命令。现在,脚本如下所示:

if [[ $a == "y" ]] ; then

    command --option 1 argument

elif [[ $a == "n" ]] ; then

    command --option 2 argument

else

    command --option 3 argument

fi
Run Code Online (Sandbox Code Playgroud)

考虑到该命令很长,并且包含许多在不同语句之间保持不变的选项和参数,我想知道是否可以以某种方式写一行,只有在相应的条件为真时才考虑可变选项。

这也适用于GNU parallel发出一个或多个命令

if [[ $b == "n" ]] ; then

    find ./ -name '*.extension' | parallel -j $(nproc) command1 --option argument

else

    find ./ -name '*.extension' | parallel -j $(nproc) command1 --option argument\; command2 --option argument
Run Code Online (Sandbox Code Playgroud)

der*_*ert 5

当然,您可以存储选项以传入变量。您的第一个示例可能是这样的(也是[[bash 功能,在 POSIX shell 中不可用):

if [[ $a == "y" ]] ; then
    arg=1
elif [[ $a == "n" ]] ; then
    arg=2
else
    arg=3
fi

command --option "$arg" argument
Run Code Online (Sandbox Code Playgroud)

你的第二个例子:

if [[ $b != "n" ]] ; then
    extra="; command2 --option argument"
fi

find ./ -name '*.extension' | parallel -j $(nproc) command1 --option argument$extra
# if unset, $extra will be empty—you can of course explicitly
# set it to '' if this bothers you.
Run Code Online (Sandbox Code Playgroud)

这些工作是因为变量扩展的工作方式:它只是被替换到命令行中,然后(如果未加引号)分词,然后传递给命令。所以被调用的命令根本不知道变量,shell 在调用它之前扩展了它们。

由于您使用的是 bash,您还可以使用数组:

args=()

if [ -n "$OPT_LONG" ]; then
    args+=(-l)
fi

if [ -n "$OPT_SORT_TIME" ]; then
    args+=(-t)
fi

ls "${args[@]}"
Run Code Online (Sandbox Code Playgroud)

数组功能让您可以轻松构建任意长的参数列表,而不必担心分词会破坏您的代码。