Wednesday, 28 November 2012

cd to directory containing a file

Many times I have run a program on a file and then immediately, wanted to change to the directory containing it, to do more operations. For example:
vim path/to/some/dir/file
then I next want to do:
cd path/to/some/dir
I used to do
cd !$
and then use the up arrow key to get the previous failed command to edit out the trailing filename and re-execute. Then I decided I should write a shell alias or function to do this. It has to be an alias or a function and not a script as cd needs to work in the current shell.

This is what I came up with:
cdf() { cd ${1%/[^/]*}; }
This uses the remove matching suffix operation of parameter substitution, see the bash manual page for details. So now I can do:
cdf !$
and I will end up in the directory containing the file I just worked on.

I picked cdf as an abbreviation for change to directory of file, but you may prefer some other name.

No comments:

Post a Comment