Reputation: 6964
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?
Upvotes: 5
Views: 1121
Reputation: 10937
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.
Upvotes: 9
Reputation: 5412
`
echo s > dummy ;
grep --color s dummy ;
if [[ $? == 2 ]]; then
echo not supported
fi
`
Upvotes: 0