bash忽略错误继续执行_忽略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.

Here is the snippet:

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 Version 3.00.16

解决方案

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

Executing it would return:

$ bash foo

1

z: line 3: some-arbitrary-command: command not found

2

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

Quote from the manual:

The shell does not exit if the command that fails is part of the

command list immediately following a while or until keyword, part of

the test in an if 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 on ERR, if set, is executed before the shell

exits.

EDIT: 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" ]]

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

This produces the following output:

$ bash foo

1

2

rm: cannot remove `MissingFile.txt': No such file or directory

Note that echo 2 was executed but echo 3 wasn't.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值