3

An Open Source project I contribute to has a dependency on which that I'd like to remove, as some Linux distros (like the cloud version of Fedora 20) don't ship with it by default, and I believe it's ugly to force its install, given how trivial our use of it is.

All we're doing is finding the path to the Java binary, then using that info to set $JAVA_HOME.

Is there a way to do that with Bash built-ins? In general, how can I somewhat-elegantly find a binary while minimizing dependencies (like which)? Or is it a better call to just use which, for example if the only alternative is to run find against directories in $PATH and the community believes that to be exceedingly inelegant?

Note that it's extremely ineffective to Google for which-related things.

2
  • 3
    It's very much better not to use which, as which is an external program using (slightly) different logic than the shell does itself, and thus can potentially give you a potentially inaccurate result! type uses the shell's built-in resolution, and is guaranteed to behave the same way the shell really will in practice. Commented May 30, 2014 at 17:50
  • I didn't know that, thanks for the bug-avoidance tip. :)
    – dfarrell07
    Commented May 30, 2014 at 17:55

3 Answers 3

7

The POSIX-ly correct way:

cmd=$(command -v whatever)
5

Maybe by parsing the output of the shell builtin type ?

~/ type python
python is /usr/bin/python
~/ type type
type is a shell builtin

Tested with zsh, bash and sh

If you are using bash, the option -P gives you directly the result you want:

~/ type -P python
/usr/bin/python
6
  • I did not mean "the program type", but the command type <program>
    – julienc
    Commented May 30, 2014 at 17:48
  • 2
    ...as using type -P will return an exact result in a manner that needs no parsing. Commented May 30, 2014 at 17:49
  • Sure, but the question specifies bash specifically. Commented May 30, 2014 at 17:50
  • You are wright, and that's why I added this example! I just did not know it as I'm usually using zsh instead of bash...
    – julienc
    Commented May 30, 2014 at 17:52
  • Thanks so much for the answer. The script in question's shebang is for bash, so this is bash-specific.
    – dfarrell07
    Commented May 30, 2014 at 17:53
1

My preference is already mentioned "type". But there is an additional command for this task:

 whereis -b <file>

locates binary for specified files

Not the answer you're looking for? Browse other questions tagged or ask your own question.