bash 脚本中的 mvn if 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13651723/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mvn in bash script if statement
提问by grivera
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
我想在 bash 脚本中运行命令 mvn clean 。但我想把它放在一个 if 语句中。如果 clean 没有正常运行,我想用 echo 语句退出 bash 脚本。这是导致问题的代码: if [ mvn clean ]; 然后
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 语句中,但是终端说参数太多。有谁知道这是否可能?谢谢!
回答by sampson-chen
Here's what you want:
这是你想要的:
mvn clean
if [ "$?" -ne 0 ]; then
    echo "Maven Clean Unsuccessful!"
    exit 1
fi
Explanation:
解释:
- $?is a special shell variablethat contains the exit code (whether it terminated successfully, or not) of the most immediate recently executed command.
- -neis an option to the- testbuiltin- [. It stands for "not equal". So here we are testing if the exit code from- mvn cleanis 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.
- $?是一个特殊的 shell 变量,它包含最近执行的命令的退出代码(无论是否成功终止)。
- -ne是- test内置的一个选项- [。它代表“不相等”。所以在这里我们测试退出代码- mvn clean是否不等于零。
- echo "Maven Clean Unsucccessful!"- 如果是这种情况,那么我们输出一些指示性消息,并以错误的退出代码退出脚本本身。
When you do $(mvn clean), that instead spawns a new subshell to run mvn clean, then simply dumps everything that was output to stdoutin that subshell from running mvn cleanto where $(...)was used in the parent shell.
当你这样做$(mvn clean),那不是产生一个新的子shell来运行mvn clean,然后简单地倾倒,这是输出到所有stdout在子shell运行mvn clean到$(...)父外壳使用。
Alternatively, you can do:
或者,您可以执行以下操作:
mvn clean || { echo "Maven Clean Unsuccessful"; exit 1; }
Which is just shorthand syntactic sugar for doing the same thing.
这只是做同样事情的速记语法糖。
回答by choroba
No parentheses needed for checking the exit status:
检查退出状态不需要括号:
if mvn clean ; then
   echo ok
else
   echo Something went wrong.
   exit 1
fi
回答by Jared
I prefer to use a variable to capture the return code. Improves readability and allows running additional commands without fear of clobbering return code value:
我更喜欢使用变量来捕获返回码。提高可读性并允许运行其他命令而不必担心破坏返回码值:
mvn clean
MVN_RTN=$?
if [ "${MVN_RTN}" -ne 0 ]; then
   echo "Maven returned failure code ${MVN_RTN}"
   exit 1
fi

