Last Updated: April 24, 2021
·
1.64K
· shawncplus

BASH history tricks

My most often used case for this is with git clone like so:

git clone host:~/repos/somerepos/mylongreponamethatidontwanttotypetwice
cd !$:t

The second command says !$ - Grab the last argument from the last command then :t - grab the 'tail' which, for a directory structure, is the last part of the path, you could also do :h to grab the directory structure up to the last part of the path

Other stuff

Everyone knows sudo !! to sudo the last command you executed but there are other tips like !git which is "Run the last git command you ran" or more usefully

!somecommand:gs/search/replace

Which will run the previous somecommand, execute a global search/replace on the command string, then execute it

Finally

!somecommand:p

Which simply prints the last somecommand that was ran and places it at the top of your history so you can press up to execute it

Further reading https://www.youtube.com/watch?v=9wcBBuZ6H4w

3 Responses
Add your response

Also with bash you can repeat the last command while replacing a string within it. So if your last command was vi file.txt and now you realize you need to edit file2.txt you can type ^file^file2 ... I know it's not a great time-saver in this example, but if you have something hidden in a long command that you need to change it's a time-saver.

over 1 year ago ·

The only downside of ^^ is that it's not a global replace, so if you had

somecommand foo bar foobar

then did

^foo^blah

You'd get

somecommand blah bar foobar

instead of

somecommand blah bar blahbar
over 1 year ago ·

but I want it to be global!
still a great trick that will stop me for hitting up and arrowing around to replace a single word. works in zsh as well

over 1 year ago ·