Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
    
Don't forget you also have tab completion and ESC dot to recall the last argument on the previous command line. –  Mark0978 Nov 18 '13 at 14:02
add comment

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

share|improve this answer
add comment

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.

share|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
add comment

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 $_)' 
share|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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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