本文介绍了bash脚本-检查输出中的特定字符串是否失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下bash脚本:
I have the following bash script:
#!/bin/sh
psql -U postgres -c "CREATE DATABASE test TEMPLATE template0;"
if [ $? -eq 0 ]; then
echo OK
else
if [ $? = 'ERROR: database "test" already exists' ]; then
echo OK
else
echo FAIL
fi
fi
当前失败,并显示以下错误:
It's currently failing with the following error:
testbox:/tmp# sh test.sh
ERROR: database "test" already exists
FAIL
我不确定我哪里出错了.对于此特定错误,我需要它返回确定".任何其他错误都应打印出失败.你能告诉我我哪里出问题了吗?
I'm not sure where I've gone wrong. I need it to return "OK" for this specific error. Any other errors should print out a FAIL.Can you tell me where I've gone wrong?
谢谢.
编辑1
我修改了代码以捕获输出,而不仅仅是rc:
I've modified the code to capture the output, not just rc:
#!/bin/bash
output=$(psql -U postgres -c "CREATE DATABASE test TEMPLATE template0;")
ret=$?
if [[ $ret -eq 0 ]]; then
echo OK
else
if [[ $output == 'ERROR: database "test" already exists' ]]; then
echo OK
else
echo FAIL
fi
fi
但我收到此错误:
ERROR: database "test" already exists
sh: ERROR: database "test" already exists: unknown operand
FAIL
推荐答案
$?
仅表示整数退出代码,而不是 psql
命令的输出.您需要获取 psql
命令的输出并检查 if
条件.
$?
represents just the integer exit code not the output of your psql
command. You need to grab the output of psql
command and check in if
condition.
您可以使用:
#!/bin/bash
output=$(psql -U postgres -c "CREATE DATABASE test TEMPLATE template0;" 2>&1)
ret=$?
if [[ $ret -eq 0 ]]; then
echo OK
else
if [[ $output == *'already exists'* ]]; then
echo OK
else
echo FAIL
fi
fi
这篇关于bash脚本-检查输出中的特定字符串是否失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!