4

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?

Community
  • 1
  • 1
Nathan Campos
  • 28,769
  • 59
  • 194
  • 300
  • Can you be a little bit more clear on what/how you would want to check? Do you want to see if a binary file/name is in your $PATH? Do you want to see if a specific rpm/dpkg is installed in the system? Please explain a little bit more. – Mattias Ahnberg Jan 07 '12 at 04:00
  • I want to check for binaries file/name on the `$PATH` – Nathan Campos Jan 07 '12 at 04:07
  • 1
    Got it. Then `hash` mentioned below is one alternative, `which` is another. :) And I agree with the others, the code is quite alright, just have to understand it and put a few newlines here and there to make more sense of it. You can strip it quite a bit depending on what you want to do. – Mattias Ahnberg Jan 07 '12 at 04:17

2 Answers2

9

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
Juliano
  • 39,173
  • 13
  • 67
  • 73
2

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
}
just somebody
  • 18,602
  • 6
  • 51
  • 60