How to Reuse Commands with the bash history Feature
Bash remembers every command you type and lets you repeat it. The quickest trick is !!, which re-runs the previous command. For older commands, press Ctrl+R and type part of the text to search backwards. This guide covers the history shortcuts that save the most time.
Show your history
The history command prints your recent commands with numbers. The file behind it is ~/.bash_history.
Repeat the last command with !!
!! reruns the previous command. It is invaluable after a failed command that needs sudo: type sudo !!.
Reuse the last argument with !$
!$ expands to the last argument of the previous command. The pattern mkdir folder then cd !$ moves into the folder you just created.
Search backwards with Ctrl+R
Press Ctrl+R, start typing part of a command, and bash shows the closest match. Press Ctrl+R again for older matches and Enter to run. This is the single most useful history shortcut.
Run a numbered command with !n
From the history listing, run any entry by number: !35 reruns entry 35. And history -c clears the current session's history.
See history for the full set of history variables.
Keep learning
Related guides: How to Kill a Process in Linux with the kill Command · How to Schedule Tasks in Linux with cron · How to Search Files for Text with the Linux grep Command. Read all tutorials on the Learn Linux blog.