If you’ve spent enough time messing around in Terminal, you’ll know one thing for sure: re-typing the stuff you’ve laboriously typed in with only minor differences is tedious. And it happens more often than we’d like.
The Terminal does, however, keep a history of all the commands you’ve typed into it. To see this in action, you can cycle through the last few commands you’ve typed in, simply hit the arrow keys up or down when in Terminal.
There are a few more less intuitive commands to make the best use of your Terminal history, however.
Let’s say you’ve just typed out a complicated command, and hit Return, only to figure out that you should have typed sudo at the beginning of the string of text. Oops! Before I learned about the double-bang symbol (!!), I would have re-typed the whole thing. Now, however, you can use the following command to use your Terminal history to better effect:
sudo !!
What this does is tell your Mac to type out the sudo command, which is used for operations that require root access to your filesystem, and then type out the last command you have written. That will run the last command with root privileges with no re-typing needed. Hooray!
How about listing all the commands you’ve written in there in the past in one fell swoop? There’s a history command that can help. Let’s say you want to see all the default commands you’ve written (the ones that change system files deep in Mac OS X)? Type the following:
history | grep defaults
You’ll get something similar to the main image at the top of this post – a long list of all the default commands you’ve issued. Yikes, that’s a lot.
See all the little numbers to the left of each of the commands? That can come in handy if you want to re-run any of the listed defaults commands. Simply type in a single bang symbol followed by the number of the line you’d like to run again, like so:
!83
This will run the command listed as line 83 again, without having to re-type. Sweet!
Via: Lifehacker