Question

I often want to change to the directory where a particular executable is located. So I'd like something like

cd `which python` 

to change into the directory where the python command is installed. However, this is obviously illegal, since cd takes a directory, not a file. There is obviously some regexp-foo I could do to strip off the filename, but that would defeat the point of it being an easy one-liner.

Was it helpful?

Solution

Here:

cd $(dirname `which python`)

Edit:

Even easier (actually tested this time):

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

Then "cdfoo python".

OTHER TIPS

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.

something like that should do the trick :

cd `dirname $(which python)`

One feature I've used allot is pushd / popd. These maintain a directory stack so that you don't have to try to keep history of where you were if you wish to return to the current working directory prior to changing directories.

For example:

pushd $(dirname `which $@`)
...
popd

You could use something like this:

cd `which <file> | xargs dirname`

I added a bit of simple error handling that makes the behavior of cdfoo() follow that of dirname for nonexistent/nonpath arguments

function cdfoo() { cd $(dirname $(which $1 || ( echo . && echo "Error: '$1' not found" >&2 ) ));}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top