Bash shell`if`命令返回`then`做某事

Bil*_*oon 12 linux bash if-statement

我正在尝试执行if/then语句,如果命令中存在非空输出,ls | grep something那么我想执行一些语句.我不知道我应该使用的语法.我尝试了几种变体:

if [[ `ls | grep log ` ]]; then echo "there are files of type log";
Run Code Online (Sandbox Code Playgroud)

Mar*_*eed 23

嗯,这是接近的,但你需要完成iffi.

此外,if只需运行命令并在命令成功时执行条件代码(以状态代码0退出),grep只有在找到至少一个匹配项时才会执行.所以你不需要检查输出:

if ls | grep -q log; then echo "there are files of type log"; fi
Run Code Online (Sandbox Code Playgroud)

如果您使用的旧版本或非GNU版本的grep系统不支持-q("安静")选项,则可以通过将其输出重定向到/dev/null以下内容来实现相同的结果:

if ls | grep log >/dev/null; then echo "there are files of type log"; fi
Run Code Online (Sandbox Code Playgroud)

但是ls如果它没有找到指定的文件也会返回非零值,你可以完全不做任何事情grep,就像D.Shawley的回答一样:

if ls *log* >&/dev/null; then echo "there are files of type log"; fi
Run Code Online (Sandbox Code Playgroud)

你也可以只用shell来做ls,尽管它有点啰嗦:

for f in *log*; do 
  # even if there are no matching files, the body of this loop will run once
  # with $f set to the literal string "*log*", so make sure there's really
  # a file there:
  if [ -e "$f" ]; then 
    echo "there are files of type log"
    break
  fi
done 
Run Code Online (Sandbox Code Playgroud)

只要您专门使用bash,就可以设置nullglob选项以简化:

shopt -s nullglob
for f in *log*; do
  echo "There are files of type log"
  break
done
Run Code Online (Sandbox Code Playgroud)