1

I am writing a script that will run several versions of a program written in different languages so it should be able to detect if the system can run a file first. I found this question somewhat useful, but I would like to know if my existing code could be improved instead.

I use the following approach to check if a program exists.

if type "$PROGRAM" >/dev/null 2>&1; then
  # OK
fi

I was debating whether this question should go in Code Review, but I decided to post it here as it's just 2 lines of code.

Community
  • 1
  • 1
Jorge Bucaran
  • 5,588
  • 2
  • 30
  • 48

1 Answers1

2

I use this in bash:

# Convenience method to check if a command exists or not.
function command_exists {
  hash "$1" &> /dev/null
}

And that gives me a command_exists:

if command_exists "vim"; then
  echo "and there was great rejoicing!"
fi

Or in one offs:

command_exists "vim" && echo "and there was great rejoicing!"

function die {
  echo "$1"
  exit 1
}
command_exists "vim" || die "Vim needs to be installed"
Sukima
  • 9,965
  • 3
  • 46
  • 60
  • Do you have any opinions for choosing `hash` over `type`? Preference? According to the linked answer, `hash` may not modify `$?` in some shells (it does not state which shells though). +1 I like `hash` in that there is no output in case of success. – Jorge Bucaran Mar 08 '15 at 05:19
  • If this was a script that would run in more then just bash then yes type is probably a better choice. But hash works on all the bash shells I've encountered so it works well for me. – Sukima Mar 08 '15 at 05:21