I was looking for a way to check if a program is installed using Shell Script when I came across this answer which contained this code:
hash foo 2>&- || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }
But that code isn't very (human) readable, what is the alternative for that syntax?
Readability is very subjective. I particularly think the original is very readable, once you know that ||
means a short-circuiting OR. So you read the original as "do this, OR this if that one fails".
The equivalent code without using ||
is:
if ! hash foo 2>&-
then
echo >&2 "I require foo but it's not installed. Aborting."
exit 1
fi
that's perfectly readable for anyone accustomed to shell scripts, because it's an idiom. the only hindrance to readability is the lack of newlines:
hash foo 2>&- || {
echo >&2 "I require foo but it's not installed. Aborting."
exit 1
}
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