shell脚本处理来自echo

时间:2016-10-26 11:25:21

标签: bash shell

您好我是shell script的新用户,我需要处理来自error内部的命令的echo,如下所示

echo -e "some internal command that I can't share \nq" | nc  localhost 10000

我想说

if [[ there's no error ]]

3 个答案:

答案 0 :(得分:0)

shell变量$?将为您提供退出代码。所以,你可以这样做:

echo -e "some internal command that I can't share \nq" | nc  localhost 10000
rc=$?

if [[ $rc == 0 ]]; then
    echo "success"
fi

或者简单地说,

if echo -e "some internal command that I can't share \nq" | nc  localhost 10000; then
    echo "success"
fi

答案 1 :(得分:0)

尝试

echo "YOUR SUPERSECRET COMMAND" | nc localhost 10000 | grep "Your expected error"
if [[ $? -eq 0 ]]; then
   echo "Do something useful with error"
else
   echo "Success"
fi

grep在匹配时返回0,并在找不到匹配的字符串时返回1.

答案 2 :(得分:0)

这是一种简洁的方法:

internalcommand &>/dev/null 2>&1 && echo OK || echo FAILED

如果internalcommand成功,OK将打印到stdout,如果失败则打印失败。

在Bash v4上测试的注释