如何解决linux输出,不需要终端输出
if(grep "9" ls ); then echo "hello"; else echo "hi"; fi
当我执行上面的命令时输出是下面的
grep: ls: No such file or directory
嗨
我怎样才能得到 hi(only condition) 作为输出
解决方法
grep -q "9" ls 2>/dev/null || echo "hi"
-q
不会打印 grep 输出本身
2>/dev/null
不是必需的,但会抑制可能的错误消息,使输出“更干净”(例如,没有 grep: ls: No such file or directory
)
或者根据 @Aaron 的建议提供更好的解决方案:
grep -qs "9" ls || echo "hi"
,
TL;博士
if( grep -q "9" ls 2>/dev/null); then echo "hello"; else echo "hi"; fi
OR
if( grep -sq 9 ls); then echo "hello"; else echo "hi"; fi
说明
您可以在终端中使用 man grep
命令查看 -q
如何抑制输出。请参阅此 gatsby-source-contentful
plugin docs 以了解为什么使用 2>/dev/null
以便不显示 STDERR。
因为 OP 的问题显示了 2 个条件。 If 和 else,我建议了这个解决方案。但是,如果您只想拥有 else
部分,则可以参考 link 答案
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。