忽略Shell脚本中的特定错误 [英] Ignoring specific errors in a shell script
问题描述
我有一小段shell脚本,有可能引发许多错误.我目前已将该脚本设置为全局停止所有错误.但是,我希望此小节有所不同.
I have a small snippet of a shell script which has the potential to throw many errors. I have the script currently set to globally stop on all errors. However i would like for this small sub-section is slightly different.
以下是代码段:
recover database using backup controlfile until cancel || true;
auto
我期望这最终会引发找不到文件"错误.但是,我想继续执行此错误.对于其他任何错误,我希望脚本停止.
I'm expecting this to eventually throw a "file not found" error. However i would like to continue executing on this error. For any other error i would like the script to stop.
实现此目标的最佳方法是什么?
What would be the best method of achieving this?
Bash版本3.00.16
Bash Version 3.00.16
推荐答案
为了防止bash忽略特定命令的错误,您可以说:
In order to prevent bash to ignore error for specific commands you can say:
some-arbitrary-command || true
这将使脚本继续.例如,如果您具有以下脚本:
This would make the script continue. For example, if you have the following script:
$ cat foo
set -e
echo 1
some-arbitrary-command || true
echo 2
执行它会返回:
$ bash foo
1
z: line 3: some-arbitrary-command: command not found
2
在命令行中没有|| true
的情况下,它会产生:
In the absence of || true
in the command line, it'd have produced:
$ bash foo
1
z: line 3: some-arbitrary-command: command not found
手册中的报价:
如果失败的命令是其中的一部分,则外壳不会退出 紧随
while
或until
关键字之后的命令列表,属于if
语句中的测试,该测试是在&&
中执行的任何命令的一部分,或者||
列表,但最后一个&&
或||
之后的命令除外 在管道中但最后一个管道中,或者命令的返回状态为 用!
反转.ERR
上的陷阱(如果已设置)在外壳程序之前执行 退出.
The shell does not exit if the command that fails is part of the command list immediately following a
while
oruntil
keyword, part of the test in anif
statement, part of any command executed in a&&
or||
list except the command following the final&&
or||
, any command in a pipeline but the last, or if the command’s return status is being inverted with!
. A trap onERR
, if set, is executed before the shell exits.
为了更改行为,以便仅在执行some-arbitrary-command
作为错误一部分返回file not found
的情况下,继续执行 ,您可以说:
In order to change the behaviour such that in the execution should continue only if executing some-arbitrary-command
returned file not found
as part of the error, you can say:
[[ $(some-arbitrary-command 2>&1) =~ "file not found" ]]
作为示例,执行以下操作(不存在名为MissingFile.txt
的文件):
As an example, execute the following (no file named MissingFile.txt
exists):
$ cat foo
#!/bin/bash
set -u
set -e
foo() {
rm MissingFile.txt
}
echo 1
[[ $(foo 2>&1) =~ "No such file" ]]
echo 2
$(foo)
echo 3
这将产生以下输出:
$ bash foo
1
2
rm: cannot remove `MissingFile.txt': No such file or directory
请注意,已执行echo 2
,但未执行.
Note that echo 2
was executed but echo 3
wasn't.
这篇关于忽略Shell脚本中的特定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!