I use a shell every day. Almost always, I want to repeat a previous command, or repeat it after a slight modification. A very convenient way is to use arrow-up to get the most recent command back. Another common trick is to type ctrl-r and incrementally search for a previously used command. However, there are two other tricks for repeating previous commands that I use all the time, which are not as well known.
Escape-Dot (or !$)
Often you want to repeat only the last argument of the previous command. For example, suppose you want to run git diff path/to/tests, and then git add path/to/tests. For the second command, you can type git add escape-dot (escape followed by a period), and it gets expanded to path/to/tests (the last argument of the previous command).
I find that I quite often want to run another command on the same argument, and escape-dot is the most convenient way to do that. It also works to use !$ instead of escape-dot, but that is slightly harder to type, so I don’t use that anymore.
History With !
Sometimes I know I used a command a while back, but I don’t have a good string for searching with in ctrl-r (or maybe I will find too many unrelated hits in the search before I find the case I want). In this case I use history to get a list of the most recently used commands. Suppose I see the command I want to repeat at position 456 in the list. The !456 will rerun the command.
If I want to modify the command before running it, I type !456:p instead. Then I use arrow-up and then modify it before running it.
I like to keep a long history for my shell commands (several thousand entries). To still be able to scroll up in my shell without only seeing history entries, I have created an alias to only show the last 100 items in the list:
alias his=’history | tail -n 100; echo “Only last 100. For full, type: history” ‘
So I usually just type his, and get the last 100 commands listed.
I often want to edit what I have on the command-line before running the command (especially if I used arrow-up to get the most recent command). Here is what I use most frequently:
- ctrl-a Move to the beginning of the line
- ctrl-e Move to the end of the line
- ctrl-u Clear the line (before the cursor position)
- ctrl-w Delete the word before the cursor position
Most people I have worked with use both arrow-up and ctrl-r when repeating commands. However, very few are familiar with escape-dot and repeating commands from the history list. Since I use all four ways very frequently, I thought I would write a post to spread the word.
On the subject of command-line shortcuts, I also have to recommend the book Unix Power Tools. It contains over a thousand pages of well-organized, cross-referenced command-line tips. A fantastic resource for anyone who wants to up their command-line game.
Be a part of something
Level up every day