嗯,差不多了,但是您需要用fi 完成if。
另外,if 仅运行命令并在命令成功时执行条件代码(以状态代码 0 退出),grep 仅在找到至少一个匹配项时才会执行此操作。所以你不需要检查输出:
if ls | grep -q log; then echo "there are files of type log"; fi
如果您使用的系统具有不支持 -q(“quiet”)选项的旧版或非 GNU 版本的 grep,您可以通过将其输出重定向到 @ 来获得相同的结果987654328@:
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