bsdfish
bsdfish

Reputation: 2454

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

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.

Upvotes: 8

Views: 730

Answers (7)

Phil P
Phil P

Reputation: 843

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.

Upvotes: 3

Dennis Williamson
Dennis Williamson

Reputation: 360625

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 ) ));}

Upvotes: 0

TheBonsai
TheBonsai

Reputation: 16545

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.

Upvotes: 8

Kam
Kam

Reputation: 321

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

Upvotes: 2

Lance Richardson
Lance Richardson

Reputation: 4610

Here:

cd $(dirname `which python`)

Edit:

Even easier (actually tested this time):

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

Then "cdfoo python".

Upvotes: 16

Rob Carr
Rob Carr

Reputation: 270

You could use something like this:

cd `which <file> | xargs dirname`

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292685

something like that should do the trick :

cd `dirname $(which python)`

Upvotes: 2

Related Questions