Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pipe multiple commands in an 'if' statement?

Tags:

linux

bash

shell

Part of a script I'm writing needs to check various text files for the same strings. Before I just had to check one file so I had a long list of strings within cateogies to search for which are defined as variables. Later on in the script the variabled are called and output to the screen if there is a match:

category_1=$(sudo zcat myfile | egrep -c 'Event 1|Event 2|Event 3')

category_2=$(sudo zcat myfile | egrep -c 'Event 4|Event 5|Event 6')

category_3=$(sudo zcat myfile | egrep -c 'Event 7|Event 8|Event 9')

...

echo Category 1

if [[ $category_1 -ge 2 ]];then

            echo There were $category_1 events

elif [[ $category_1 -eq 1 ]]; then

            echo There was $category_1 event

fi

etc, etc...

Now I need to change it so that I can check the grepped strings against multiple text files. I've tried to define the new files as variables and pipe them in the if statement with the grep variable to no avail:

category_1=$(egrep -c 'Event 1|Event 2|Event 3')

category_2=$(egrep -c 'Event 4|Event 5|Event 6')

category_3=$(egrep -c 'Event 7|Event 8|Event 9')


myfile=$(sudo zcat myfile)

myfile2=$(sudo zcat myfile2)

myfile3=$(sudo zcat myfile3)

...

echo Category 1 - Myfile



if [[ myfile | $category_1 -ge 2 ]];then

            echo There were $category_1 events in myfile

elif [[ myfile | $category_1 -eq 1 ]]; then

            echo There was $category_1 event in myfile

fi

It seems that I can't pipe commands in an if statement.

like image 787
XOR Avatar asked Dec 16 '13 14:12

XOR


1 Answers

Use $(...) to capture output of a command into a string:

if  [[ $(sudo zcat myfile1 | egrep -c 'Event 1|Event 2|Event 3') -ge 2 ]] ; then
like image 188
choroba Avatar answered Oct 14 '22 10:10

choroba