如何执行命令,如果失败,执行另一个命令并返回1?

Cho*_*per 5 linux bash

我已经习惯了其他语言的这种风格:

do_something || (log_error; return 1) # do something, and if that fails, log the error and then return 1 no matter what, even if the logging fails.
Run Code Online (Sandbox Code Playgroud)

但我似乎无法在 bash 中找到等价物。问题是括号的工作有点像一个有自己作用域的函数,返回 1 不会有预期的行为。

到目前为止,这是我所拥有的,但并不完美:

! do_something && log_error && return 1
Run Code Online (Sandbox Code Playgroud)

问题在于!令人困惑,返回1取决于日志记录的成功。

这个更好,但更冗长:

do_something || (log_error; return 1) || return 1
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Bat*_*hyX 11

使用大括号。

 do_something || { log_error; return 1;}
Run Code Online (Sandbox Code Playgroud)