首页 > 解决方案 > 使用 ls | grep 在 if 语句中

问题描述

我正在尝试使用 if [grep] 使用退出值来触发它

从命令行进行测试

$ ls ~/dir | grep txt
$ echo $?
0

但是,当我在脚本的 if 语句中使用它时,即

if [ ls /some/dir | grep -q pattern ]; then
    echo y
fi

它说

line 1: [ missing `]' (the line the if statement was written on)

为什么会发生这种情况,有没有办法解决它?

标签: bash

解决方案


那是因为[is 和条件表达式,请查看详细信息

您应该()改用:

if (ls /some/dir | grep -q pattern); then
    echo y
fi

推荐阅读