Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash shortcut to get parent of last used parameter

Tags:

bash

In my workflow I do very usually:

cat this/very/long/filename.txt cd !$ bash: cd: this/very/long/filename.txt: Not a directory 

Which is to be expected :(

And now I recover the last command, remove manually the file part, and repeat the cd, which now works. That is too much typing!

It would be sooo nice if there was a bash shortcut like:

cd !§ 

Which could give me the parent of the last used parameter. I know does not exist, I just wished it did! Is there something which can satisfy this?

like image 642
blueFast Avatar asked Jul 30 '14 13:07

blueFast


2 Answers

Et voilà. History modifiers come to the rescue!

$ cd !!:$:h 

which can be abbreviated to

$ cd !$:h 

This command takes the last argument of the previous command, and removes the trailing path name.

In more details:

  1. !! expands to the previous command
  2. :$ expands to the last argument of the previous command
  3. :h takes the header; that is, removes the file name (which is the trailing part of the above last argument)

As an aside,

!!:$:t 

does exactly the opposite.

For an in-depth discussion, please refer to the Bash documentation.

like image 160
Roberto Reale Avatar answered Sep 20 '22 22:09

Roberto Reale


This shorter version would also work:

cd !$:h 

Details:

  • !$ is synonymous to !!:$ which presents the last argument of the previous command.
  • : separates the modifier from the event-word designator.
  • h is the modifier that removes the trailing file name component.
like image 21
konsolebox Avatar answered Sep 18 '22 22:09

konsolebox