Bash `if` command shell returns something` something` do something

I am trying to make an if / then statement, where if there is non-empty output from the ls | grep something ls | grep something , then I want to fulfill some statements. I do not know what syntax I should use. I tried several variations of this:

 if [[ `ls | grep log ` ]]; then echo "there are files of type log"; 
+6
source share
3 answers

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 # 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 really # a file there: if [ -e "$f" ]; then echo "there are files of type log" break fi done 

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 
+18
source

Or without if; then; fi if; then; fi if; then; fi :

 ls | grep -q log && echo 'there are files of type log' 

Or even:

 ls *log* &>/dev/null && echo 'there are files of type log' 
+2
source

The built-in if executes a shell command and selects a block based on the return value of the command. ls returns a separate status code if it does not find the requested files, so there is no need for the grep part. The utility [[ is actually a built-in command from bash, IIRC, which performs arithmetic operations. I could be wrong in this part, since I rarely deviated from the Bourne shell syntax.

In any case, if you put all this together, you will get the following command:

 if ls *log* > /dev/null 2>&1 then echo "there are files of type log" fi 
+1
source

Source: https://habr.com/ru/post/914462/


All Articles