supertonic09 supertonic09 - 3 months ago 20
Linux Question

Universal approach to grep for both Linux and Solaris

I have a relative long collection of scripts that I'm currently evaluating, and making changes to the source in order to execute the same set of scripts in both Linux and SunOS boxes. Part of the code has a simple grep like this:

#Linux
echo -e "\n foo \n bar \n test ok" | grep -Evw 'foo|bar'


My porting attempt works fine if translated as:

#SunOS
echo -e "\n foo \n bar \n test ok" | /usr/xpg4/bin/grep -Ev 'foo|bar'


Is there a way to write a single statement in Bash to work in both scenarios? Or, should I be mentally prepared to start implemting additional if/else statements for each operating system?

In this case, it seems like /bin/grep can do both regex and word matching, but then with /usr/bin/grep we can only do word and not both:

$ echo -e "\n foo \n bar \n test ok" | grep -Evw 'foo|bar'
grep: illegal option -- E
Usage: grep [-c|-l|-q] -bhinsvw pattern file . . .
$ echo -e "\n foo \n bar \n test ok" | /usr/xpg4/bin/grep -Evw 'foo|bar'
Usage: grep [-c|-l|-q] [-bhinsvwx] pattern_list [file ...]
grep [-c|-l|-q] [-bhinsvwx] [-e pattern_list]... [-f pattern_file]... [file...]
grep -E [-c|-l|-q] [-bhinsvx] pattern_list [file ...]
grep -E [-c|-l|-q] [-bhinsvx] [-e pattern_list]... [-f pattern_file]... [file...]
grep -F [-c|-l|-q] [-bhinsvx] pattern_list [file ...]
grep -F [-c|-l|-q] [-bhinsvx] [-e pattern_list]... [-f pattern_file]... [file...]

Answer

How about putting something like that at the top of your scripts:

[ -d /usr/xpg4/bin ] && PATH="/usr/xpg4/bin:$PATH"

Then the following line will work on both systems:

echo -e  "\n foo \n bar \n test ok" | grep -Evw 'foo|bar'

The idea of course is to check if the directory /usr/xpg4/bin exists, and if does, we may assume that it includes a grep that supports the options that we want (presumably the GNU grep). So just add that dir at the beginning of $PATH so that it takes the highest priority.