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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With