linux - Bash shell `if` 命令返回一些东西 `then` 做一些事情

标签 linux bash if-statement

我正在尝试做一个 if/then 语句,如果 ls | 有非空输出grep something 命令然后我想执行一些语句。我不知道我应该使用的语法。我已经尝试了几种变体:

if [[ `ls | grep log ` ]]; then echo "there are files of type log";

最佳答案

好吧,这很接近,但是您需要用 fi 完成 if

此外,if 只是运行一个命令,如果命令成功则执行条件代码(以状态码 0 退出),而 grep 只有在找到至少一场比赛。所以你不需要检查输出:

if ls | grep -q log; then echo "there are files of type log"; fi

如果您使用的是不支持 -q(“quiet”)选项的旧版本或非 GNU 版本的 grep,您可以通过将其输出重定向到 /dev/null 来实现相同的结果:

if ls | grep log >/dev/null; then echo "there are files of type log"; fi

但是因为 ls 如果没有找到指定的文件也会返回非零值,你可以在没有 grep 的情况下做同样的事情,就像 D.Shawley 的回答:

if ls *log* >&/dev/null; then echo "there are files of type log"; fi

你也可以只使用 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 

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

shopt -s nullglob
for f in *log*; do
  echo "There are files of type log"
  break
done

关于linux - Bash shell `if` 命令返回一些东西 `then` 做一些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10372626/

相关文章:

linux - 什么会导致 gcc 不再识别 "bool"?

c - 如何在终端中输入/输入特殊字符 ETB(ASCII 23) 作为字符?

linux - bash - 如何将换行符传递给脚本?

Javascript 三元 if 语句,将其分配给变量并递增

java - 如果...则加载 .sav 文件后比较器失败

python-3.x - 遍历列表字典并更新相应的列 - pandas

java - 找不到主类: SortAlgorithms

MySQL统计输出

bash - 在 Bash 中如何检查一个变量是否至少包含一个字母字符?

bash - Linux shell - 解析奇怪格式的日期