Shell – How to return the directory of a given executable

shellwhich

If I want to return the path of a given executable, I can run:

which mysql

Which returns for example:

/usr/bin/mysql

I'd like to return only:

/usr/bin

How can I do that?

Best Answer

executable=mysql

executable_path=$(command -v -- "$executable") &&
  dirname -- "$executable_path"

(don't use which).

Of course, that won't work if $executable is a shell builtin, function or alias. I'm not aware of any shell where mysql is a builtin. It won't be a function or alias unless you defined them earlier, but then you should know about it. An exception to that could be bash which supports exported functions.

$ bash -c 'command -v mysql'
/usr/bin/mysql
$ mysql='() { echo test;}' bash -c 'command -v mysql'
mysql
Related Question