A bash one-liner to change into the directory where some file is located

Here:

cd $(dirname `which python`)

Edit:

Even easier (actually tested this time):

function cdfoo() { cd $(dirname `which $@`); }

Then "cdfoo python".


To avoid all those external programs ('dirname' and far worse, the useless but popular 'which') maybe a bit rewritten:

cdfoo() {
  tgtbin=$(type -P "$1")
  [[ $? != 0 ]] && {
    echo "Error: '$1' not found in PATH" >&2
    return 1
  }
  cd "${tgtbin%/*}"
}

This also fixes the uncommon keyword 'function' from above and adds (very simple) error handling.

May be a start for a more sphisticated solution.


For comparison:

zsh:~% cd =vi(:h)
zsh:/usr/bin%

=cmd expands to the path to cmd and (:h) is a glob modifier to take the head

zsh is write-only but powerful.

Tags:

Bash

Cd