If you set environment variables like your $EDITOR in your .bashrc file
that refer to commands that you expect to be available on the system, it’s
prudent to check that an appropriate command actually exists before making the
setting.
A common way of approaching this is using which, in a syntax similar to the
below, which sets the $EDITOR to the first executable instance of vi found
in $PATH, or blank if not found:
EDITOR=`which vi`
Because the behaviour of which can be unexpected, it’s better practice
to use one of Bash’s builtins to do this, either command, type, or hash.
I prefer using hash, which searches $PATH for a command of the given name,
and loads it into Bash’s command hash table if found. An implementation like
the below works well:
hash vi &>/dev/null
if [ $? -eq 0 ]; then
export EDITOR=vi
fi
This ignores any output from the hash call by redirecting it to the null
device, and checks its return value in the special $? variable, only defining
the value for $EDITOR if a matching command is found.
You can compact this syntax into one line:
hash vi &>/dev/null && export EDITOR=vi
Thanks to commenter Yu-Jie Lin for pointing out the above abbreviation.
You don’t need to check $?, you can directly check the exit status with if:
if hash vi &>/dev/null; then export EDITOR=vi fi
or just
hash vi &>/dev/null && export EDITOR=vi
That one is really useful for my bashrc. Where do you learn all that stuff?
a bit here and a bit there. But most of stuff are from the manpage. I can always learn something everytime I read Bash manpage. Bash is a huge thing.
Yes, that’s much nicer for those who value compactness. Added to the post. Thank you!
I’m using type -P instead of which
Yep! Works just as well.