Reputation: 5666
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.
Upvotes: 1
Views: 99
Reputation: 10064
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"
Upvotes: 2