Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash shell 'if' statement comparing outputs from different commands

Using an adapted example given to me by Sam Ruby which I have tweaked so I can show what I'm trying to achieve.

app1=$(someapp -flag | grep usefulstuff | cut -c 5-10)
if [$app1 = (someapptwo -flag | grep usefulstuff | cut -c 20-25)]; then
mkdir IPFolder-1
elif ...blah blah
fi 

Can I use grep as show above or am I barking up the wrong tree? or should it look a little some thing like this:

app1=$(someapp -flag | grep usefulstuff | cut -c 5-10)
app2=$(someapptwo -flag | grep usefulstuff | cut -c 20-25)
if [$app1 = $app2]; then
mkdir IPFolder-1
elif ...blah blah
fi 
like image 435
bikerben Avatar asked Dec 06 '25 08:12

bikerben


2 Answers

At least in other shells, you need to be a lot more careful with spaces; the square bracket is a command name and needs to be separated from previous and following words. You also need (again in classic shells for certain) to embed the variables in double quotes:

app1=$(someapp -flag | grep usefulstuff | cut -c 5-10)
if [ "$app1" = "$(someapptwo -flag | grep usefulstuff | cut -c 20-25)" ]
then mkdir IPFolder-1
elif ...blah blah
then : do this instead...
fi

You could do it all in one line (well, two because I avoid the horizontal scrollbar whenever possible):

if [ "$(someapp    -flag | grep usefulstuff | cut -c  5-10)" = \
     "$(someapptwo -flag | grep usefulstuff | cut -c 20-25)" ]
then mkdir IPFolder-1
elif ...blah blah
then : do this instead...
fi

Or you could do it with two separate command captures:

app1=$(someapp    -flag | grep usefulstuff | cut -c  5-10)
app2=$(someapptwo -flag | grep usefulstuff | cut -c 20-25)
if [ "$app1" = "$app2" ]
then mkdir IPFolder-1
elif ...blah blah
then : do this instead...
fi

Update: Some extra quotes added. It would be possible to quote the assignments too:

app1="$(someapp -flag | grep usefulstuff | cut -c  5-10)"

No harm would be done; it isn't strictly necessary with bash (but it may well have been necessary with archaic Bourne shell).

like image 103
Jonathan Leffler Avatar answered Dec 08 '25 21:12

Jonathan Leffler


You need to refer to the value of your expression by prepending a $:

...
if [ "$app1" = "$(someapptwo -flag | grep usefulstuff | cut -c 20-25)" ]; then
...
like image 31
milancurcic Avatar answered Dec 08 '25 22:12

milancurcic