如何测试命令是否失败或返回特定输出?

问题描述 投票:0回答:1

我有一个带有命令的 bash 脚本,我想测试命令是否失败或返回与正则表达式匹配的输出。像这样的东西:

commandOutput = command()

if (commandOutput.exitCode = ERROR or commandOutput.matches(string|strong) then
    doStuffOnError()
end

如何在 shell 脚本中执行此操作?

bash shell
1个回答
0
投票

既然你专门要求BASH代码,我将使用

[[]]
,它仅在BASH中可用。
您可以使用以下代码做您想做的事:

commandOutput=$(command)
if [[ $? -ne 0 || commandOutput == *"string"* || commandOutput == *"strong"* ]]; then
    doStuffOnError
fi
    

说明:

    shell中的
  • $?
    是上一个命令的退出码
  • 我们检查它是否非零(也就是以错误结束)或者输出是否匹配“string”或“strong”,如果其中任何一个为真,那么我们执行
    duStuffOnError

请注意,此处

commandOutput
仅存储
stdout
上的内容。
如果您还想要
stderr
,请考虑
commandOutput=$(command 2>&1)
,它将
stderr
重定向到
stdout

© www.soinside.com 2019 - 2024. All rights reserved.