I frequently have to do this. For example:

$ vim /etc/pam.d/sudo
$ vim /etc/pam.d/sudo-i
$ cd /etc/pam.d/  # Figure I should just go to the directory

Now, is there a way I could obtain the directory of the last argument when it's a file path? What I'm hoping for is something like this:

$ vim /etc/pam.d/sudo
$ vim /etc/pam.d/sudo-i
$ cd $dir # <-- something that returns /etc/pam.d in this case

I'm asking this cause I recently became aware of the $_ variable that has become useful. Was wondering if there's some other commandline fu that might come in handy.

link|improve this question

feedback

3 Answers

up vote 2 down vote accepted

While I would use BillThor's answer, there is a purely bash answer:

$ ls /etc/pam.d/sudo
$ cd !$:h

See History Interaction in the bash manual

link|improve this answer
feedback

The bash history is effectively a text file listing the previously executed commands - it doesn't include any metadata saying what those commands are doing, and what type of parameters are being passed.

So $_ just contains the content after the last space.

I think the answer is no, there isn't any way to do this with bash, you'd probably need a custom shell.

link|improve this answer
I was thinking it might be unlikely. Looked through the manpage and didn't see anything that seemed applicable. Figured I'd ask just in case. – Beaming Mel-Bin Nov 15 '11 at 2:06
feedback

Try

 $(dirname $_)

This will give you the directory above whatever was the last argument. Returns . if the there is no directory component. Also if the argument was something like /etc/pam.d/, it will return /etc.

Adding the following to your .profile file will let you do what you want with the command cdx:

alias cdx='cd $(dirname $_)' 
link|improve this answer
Ladies and gentlemen, this is why stack exchange rocks. Was a shot in the dark. Thanks for the tip! – Beaming Mel-Bin Nov 15 '11 at 2:22
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.