我正在尝试做一个 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/