bash脚本中的mvn if语句 [英] mvn in bash script if statement
问题描述
我想在bash脚本中运行命令mvn clean.但我想将其放在if语句中.如果清理无法正常运行,我希望使用echo语句退出bash脚本. 这是导致问题的代码: 如果[mvn clean];然后
I want to run the command mvn clean in a bash script. But I want to put it in an if statement. If the clean does not run properly I would like to exit out of the bash script with an echo statement. Here is the code that is causing the problem: if [ mvn clean ]; then
我尝试将$(mvn clean)放在if语句中,但是终端说参数太多.有人知道这是否可能吗?谢谢!
I tried putting $(mvn clean) inside the if statement but there were too many arguments says the terminal. Does anyone know if this is possible? Thanks!
推荐答案
这就是您想要的:
mvn clean
if [ "$?" -ne 0 ]; then
echo "Maven Clean Unsuccessful!"
exit 1
fi
说明:
-
$?
是特殊shell变量,其中包含退出最近执行的最近命令的代码(是否成功终止). -
-ne
是test
mvn clean的退出代码是否不等于零. -
echo "Maven Clean Unsucccessful!"
-如果是这种情况,则我们输出一些指示性消息,并使用错误的退出代码退出脚本本身.
$?
is a special shell variable that contains the exit code (whether it terminated successfully, or not) of the most immediate recently executed command.-ne
is an option to thetest
builtin[
. It stands for "not equal". So here we are testing if the exit code frommvn clean
is not equal to zero.echo "Maven Clean Unsucccessful!"
- If this is the case, then we output some indicative message, and exit the script itself with an errant exit code.
当您执行$(mvn clean)
时,它会生成一个新的子Shell来运行mvn clean
,然后只需将该子Shell中输出到stdout
的所有内容从运行mvn clean
转储到在其中使用$(...)
父外壳.
When you do $(mvn clean)
, that instead spawns a new subshell to run mvn clean
, then simply dumps everything that was output to stdout
in that subshell from running mvn clean
to where $(...)
was used in the parent shell.
或者,您可以执行以下操作:
Alternatively, you can do:
mvn clean || { echo "Maven Clean Unsuccessful"; exit 1; }
这只是做同一件事的简写语法糖.
Which is just shorthand syntactic sugar for doing the same thing.
这篇关于bash脚本中的mvn if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!