Check if the command is supported.

In my .bashrc , I want alias grep to be grep --color if the --color option is supported. But --color not supported on older systems like msysgit:

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

In .bashrc, how can I determine if an option is supported? I can check the hard-coded version number, but this 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 check if a command supports a parameter?

+4
source share
2 answers

Take the grep command, which, as you know, will succeed and add a color parameter.

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

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

So your bashrc will look like this:

 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 does not work, it is disabled. But it still returns an error code that prevents the setting of an alias.

+8
source
 ` echo s > dummy ; grep --color s dummy ; if [[ $? == 2 ]]; then echo not supported fi ` 
0
source

All Articles