Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

cd

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.

like image 763
bsdfish Avatar asked May 13 '09 01:05

bsdfish


2 Answers

Here:

cd $(dirname `which python`)

Edit:

Even easier (actually tested this time):

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

Then "cdfoo python".

like image 151
Lance Richardson Avatar answered Sep 21 '22 17:09

Lance Richardson


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.

like image 29
TheBonsai Avatar answered Sep 21 '22 17:09

TheBonsai