Johan Vergeer
Johan Vergeer

Reputation: 5568

Get directory of an executable using which

I would like to use the which command to cd directly into a directory.

cd $(which python3.6)

Obviously this will not work, since which python3.6 will return an executable.

Now the question is: how can I cd into the location of this executable?

Upvotes: 2

Views: 106

Answers (2)

Micah Elliott
Micah Elliott

Reputation: 10274

Presuming you're using Zsh as tagged, you can use some short notation to get there:

cd =python3.6(:h)

The = expansion is essentially a shortcut for which. The :h is to take the "head" of the path, thus equivalent to dirname. See man zshexpn for details on the :h modifier and others.

Upvotes: 4

Ayman Nedjmeddine
Ayman Nedjmeddine

Reputation: 12699

Use dirname:

cd `dirname $(which python3.6)`

From man(1) page:

Name:
dirname - strip non-directory suffix from file name

Synopsis:
dirname NAME
dirname OPTION

Description:
Print NAME with its trailing /component removed; if NAME contains no /'s, output '.' (meaning the current directory).

Upvotes: 4

Related Questions