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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With