这里的目标是使用相同的脚本执行四个随机单词,而不必重复它。
到目前为止,脚本接收单词并说明该单词是成功(命令)还是失败(不是命令)。但是,我必须重复它才能使其工作。如果我使用 || 或 &&,它们仍然被视为一个命令/单词。
我想要插入的单词是 date、date blah、someoneexistingcommand
我怎样才能更有效地做到这一点?
date
and then check the exit status:
if test $? ==0
then
echo valid
else
echo invalid
fi
date blah
and then check the exit status:
if test $? ==0
then
echo valid
else
echo invalid
fi
someexistingcommand
and then check the exit status:
if test $? ==0
then
echo valid
else
echo invalid
fi
谢谢
答案1
我会使用for
循环构造。从help for
bash 5.0.16 开始:
for: for NAME [in WORDS ... ] ; do COMMANDS; done
Execute commands for each member in a list.
The `for' loop executes a sequence of commands for each member in a
list of items. If `in WORDS ...;' is not present, then `in "$@"' is
assumed. For each element in WORDS, NAME is set to that element, and
the COMMANDS are executed.
Exit Status:
Returns the status of the last command executed.
虽然不清楚您将如何向脚本提供命令,而且我也没有要求澄清的资格。假设命令将在您的脚本中硬编码,则以下内容将起作用:
单行表格:
for command in "date" "date blah" "someoneexistingcommand"; do if $command; then echo valid; else echo invalid; fi; done
多行表格:
for command in "date" "date blah" "someoneexistingcommand"; do
if $command; then
echo valid
else
echo invalid
fi
done
具体来说:
遍历列表,将当前值临时分配给名为“command”的变量。请注意,“command”可以是任何有效的变量名。“list”是“in”之后和命令分隔符(在本例中为分号“;”)之前的每个单词
for command in "date" "date blah" "someoneexistingcommand"; do
针对 的每个值都将执行以下命令$command
。运行命令并同时测试其退出状态。使用“$?”是多余的。
if $command; then
echo valid
else
echo invalid
fi
我们已运行完命令。离开 for 循环。
done
以下大致相同:
if date; then
echo valid
else
echo invalid
fi
if date blah; then
echo valid
else
echo invalid
fi
if someoneexistingcommand; then
echo valid
else
echo invalid
fi