Search code examples
linuxbashzsh

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?


Solution

  • 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).