There is no need to recall a command from an hour ago letter by letter: the shell remembers it for you.
The Up arrow brings back the previous command, further presses bring older ones, and the Down arrow newer ones. You can edit the recalled line before Enter. history prints the whole list with numbers, dates and times:
The command history keeps typos and commands that failed too. The same command typed several times in a row is stored once. History does not remember how a command turned out: it stores lines.
An old command is faster to find by searching. Ctrl+R opens a search through history: type part of a command, and the latest match appears on the line. Each further Ctrl+R finds an earlier match. The next key decides what happens to the line found:
| Key | What happens to the found line |
|---|---|
| Enter | it runs at once |
| → | it stays on the line for editing |
| Ctrl+G | it is gone: the search closes and the old line returns |
A password typed right into a command stays in the history. Do not put secrets on the command line.
Ctrl+R with the word host found sudo hostname web-01. You need the same command but with the name web-02. What do you do?
-
historyprints the list of commands with numbers and times and runs nothing. The Right arrow is what keeps the found line for editing. -
Ctrl+G closes the search and restores the line as it was before Ctrl+R, so the found command disappears. The Right arrow is what keeps it for editing.
-
Enter in the search runs what it found at once: the machine gets the name web-01. Check
hostnameafter such an Enter.
The Right arrow leaves the found line on the command line so you can edit it. Enter in the search would run sudo hostname web-01 as is, and Ctrl+G would close the search and bring back the old line.
Key points
- The Up and Down arrows move through history; you can edit a recalled line before Enter.
- Ctrl+R searches history: Enter runs the match at once, the Right arrow keeps it for editing.