Ok, this is close, but you need to end the if
with fi
.
In addition, if
runs only the command and executes conditional code if the command succeeds (ends with status code 0), which grep
executes only if it finds at least one match. Therefore, you do not need to check the output:
if ls | grep -q log; then echo "there are files of type log"; fi
If you are using a system with an old or non-GNU version of grep
that does not support the -q
("quiet") option, you can achieve the same result by redirecting its output to /dev/null
:
if ls | grep log >/dev/null; then echo "there are files of type log"; fi
But since ls
also returns a nonzero value if it does not find the specified file, you can do the same without grep
at all, as in D.Shawley's answer:
if ls *log* >&/dev/null; then echo "there are files of type log"; fi
You can also do this using only the shell, even without ls
, although this is a bit more verbose:
for f in *log*; do
As long as you use bash specifically, you can set the nullglob
parameter to simplify this:
shopt -s nullglob for f in *log*; do echo "There are files of type log" break done
source share