Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether a command option is supported

Tags:

bash

shell

In my .bashrc, I want to alias grep to grep --color if the --color option is supported. But --color isn't supported on old systems like msysgit:

$ grep --color
grep: unrecognized option '--color'
$ grep --version
grep (GNU grep) 2.4.2

In .bashrc, how can I determine whether an option is supported? I can test for a hard-coded version number, but that will break for versions >2.5:

if [[ `grep --version` == *2.5* ]] ; then
    alias grep='grep --color=auto'
fi

Is there a more reliable way to test if a command supports an option?

like image 272
Justin M. Keyes Avatar asked Jan 11 '13 15:01

Justin M. Keyes


1 Answers

Take a grep command which you know will succeed and add the color option E.g.

grep --color "a" <<< "a"

the return code will be 0 if the option exists, and positive otherwise.

So your bashrc will look like:

if grep --color "a" <<<"a" &>/dev/null; then
    alias grep='grep --color=auto'
fi

&> sends stdout and stderr to /dev/null, so if the command fails, it is silenced. But it still returns an error code, which prevents the alias from being set.

like image 126
cmh Avatar answered Oct 28 '22 21:10

cmh