我有一个带有命令的 bash 脚本,我想测试命令是否失败或返回与正则表达式匹配的输出。像这样的东西:
commandOutput = command()
if (commandOutput.exitCode = ERROR or commandOutput.matches(string|strong) then
doStuffOnError()
end
如何在 shell 脚本中执行此操作?
既然你专门要求BASH代码,我将使用
[[]]
,它仅在BASH中可用。commandOutput=$(command)
if [[ $? -ne 0 || commandOutput == *"string"* || commandOutput == *"strong"* ]]; then
doStuffOnError
fi
说明:
$?
是上一个命令的退出码duStuffOnError
请注意,此处
commandOutput
仅存储 stdout
上的内容。stderr
,请考虑 commandOutput=$(command 2>&1)
,它将 stderr
重定向到 stdout
。