bash:在 if 语句中使用 grep,防止回声

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14407229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:18:09  来源:igfitidea点击:

bash: using grep in if statement, prevent echo

bashif-statementgrep

提问by Chris Seymour

I have this bash script:

我有这个 bash 脚本:

#!/bin/bash

external_output="Oliver's AirPort Express"

if ~/.bin/audiodevice | grep "$external_output"
then
  ~/.bin/audiodevice output "Internal Speakers"
  echo "Internal Speakers"
else
  ~/.bin/audiodevice output "$external_output"
  echo "Oliver's AirPort Express"
fi

If the grepis matched, then it of course echoes the match. As I am using it in an if statement, I don't want this to echo.

如果grep匹配,那么它当然会回显匹配。当我在 if 语句中使用它时,我不希望它回响。

How can I use grepin my ifstatement without having it announce the result to me when I run the script?

如何grep在我的if语句中使用而不在我运行脚本时向我宣布结果?

回答by Chris Seymour

You want grep -q "$external_output"to suppress the output. From man grep:

您想grep -q "$external_output"抑制输出。来自man grep

-q, --quiet, --silent

Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected (-q is specified by POSIX).

-q, --quiet, --silent

安静的; 不要向标准输出写入任何内容。如果找到任何匹配项,则立即以零状态退出,即使检测到错误(-q 由 POSIX 指定)。