Shrey
Shrey

Reputation: 689

Finding if 'which' command is available on a System through BASH

While writing BASH scripts, I generally use the which command of a Linux machine (where Linux Machine refers to Desktop based Linux OS like Ubuntu, Fedora, OpenSUSE) for finding path or availability of other binaries. I understand that which can search for binaries (commands) which are present in the PATH variable set.

Now, I am unable to understand how to proceed in case the which command itself is not present on that machine.

My intention is to create a shell script (BASH) which can be run on a machine and in case the environment is not adequate (like some command being used in script is missing), it should be able to exit gracefully.

Does any one has any suggestions in this regard. I understand there can be ways like using locate or find etc - but again, what if even they are not available. Another option which I already know is that I look for existence of a which binary on standard path like /usr/bin/ or /bin/ or /usr/local/bin/. Is there any other possibility as well?

Thanks in advance.

Upvotes: 1

Views: 345

Answers (2)

Ray Toal
Ray Toal

Reputation: 88378

(More of a comment because Boldewyn answered perfectly, but it is another take on the question that may be of interest to some.)

If you are worried that someone may have messed with your bash installation and somehow removed which, then I suppose in theory, when you actually invoked the command you would get an exit code of 127.

Consider

$ sdgsdg
-bash: sdgsdg: command not found
$ echo $?
127

Exit codes in bash: http://tldp.org/LDP/abs/html/exitcodes.html

Of course, if someone removed which, then I wouldn't trust the exit codes, either.

Upvotes: 3

Boldewyn
Boldewyn

Reputation: 82734

type which

type is a bash built-in command, so it's always available in bash. See man bash for details on it.

Note, that this will also recognize aliases:

$ alias la='ls -l -a'
$ type la
la is aliased to 'ls -l -a'

Upvotes: 8

Related Questions