在 bash 脚本中使用标志
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39672509/
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
use of flags in bash script
提问by iwekesi
Scripts in linux start with some declaration like :
linux 中的脚本以一些声明开头,例如:
#!/bin/bash
#!/bin/bash
Correct me if I am wrong : this probably says which shell to use.
如果我错了,请纠正我:这可能说明要使用哪个 shell。
I have also seen some scripts which say :
我还看到一些脚本说:
#!/bin/bash -ex
#!/bin/bash -ex
what is the use of the flags -ex
标志 -ex 的用途是什么
回答by pavnik
#!/bin/bash -ex
<=>
#!/bin/bash
set -e -x
Man Page (http://ss64.com/bash/set.html):
手册页 ( http://ss64.com/bash/set.html):
-e Exit immediately if a simple command exits with a non-zero status, unless
the command that fails is part of an until or while loop, part of an
if statement, part of a && or || list, or if the command's return status
is being inverted using !. -o errexit
-x Print a trace of simple commands and their arguments
after they are expanded and before they are executed. -o xtrace
UPDATE:
更新:
BTW, It is possible to set switches without script modification.
顺便说一句,无需修改脚本即可设置开关。
For example we have the script t.sh
:
例如,我们有脚本t.sh
:
#!/bin/bash
echo "before false"
false
echo "after false"
And would like to trace this script: bash -x t.sh
并想跟踪这个脚本: bash -x t.sh
output:
output:
+ echo 'before false'
before false
+ false
+ echo 'after false'
after false
For example we would like to trace script and stop if some command fail (in our case it will be done by command false
): bash -ex t.sh
例如,我们想跟踪脚本并在某些命令失败时停止(在我们的例子中它将由 command 完成false
):bash -ex t.sh
output:
output:
+ echo 'before false'
before false
+ false
回答by Matei David
These are documented under set
in the SHELL BUILTIN COMMANDS
section of the man page:
这些记录在手册页set
的SHELL BUILTIN COMMANDS
部分中:
-e
will cause Bash to exit as soon as a pipeline (or simple line) returns an error-x
will case Bash to print the commands before executing them
-e
一旦管道(或简单的行)返回错误,就会导致 Bash 退出-x
将案例 Bash 在执行之前打印命令
回答by Gilles Quenot
-e
is to quit the script on any error
是在出现任何错误时退出脚本
-x
is the debug mode
是调试模式
Check bash -x commandand What does set -e mean in a bash script?