Updated: 28 September 2026 · Applies to: bash 5.1 to 5.3 on AlmaLinux and Rocky Linux 9 and 10, RHEL 9 and 10, Ubuntu 24.04 and 26.04, Debian 13
Retyping long commands wastes time. Bash keeps a history of what you ran and offers several ways to run a command again, or to reuse part of it.
1. The arrow keys and Ctrl+R
- Up arrow: show the previous command; press Enter to run it, or edit it first.
- Ctrl+R, then type part of a command: search the history backwards. Press Ctrl+R again for older matches, Enter to run, or the right arrow to edit.
2. History expansion with !
!! # the last command sudo !! # the last command, now with sudo !-2 # the command before the last one !systemctl # the last command that started with "systemctl" !42 # command number 42 from the history list !$ # the last word of the previous command (often a file name)
Bash prints the expanded command before running it. To see it without running it first, add :p, for example !systemctl:p.
3. fc: edit, then run
fc # open the last command in your editor, run it after saving fc -s # run the last command again fc -s old=new # run the last command with "old" replaced by "new"
Example: after systemctl status nginx, the command fc -s status=restart runs systemctl restart nginx. The shorter form ^status^restart does the same.
4. Browse the history
history | tail -20 history | grep certbot
Useful history settings
Add to ~/.bashrc for a longer, timestamped history:
HISTSIZE=10000 HISTFILESIZE=20000 HISTTIMEFORMAT='%F %T ' shopt -s histappend
histappend keeps commands from several open terminals instead of overwriting them. A command that starts with a space is not saved when HISTCONTROL contains ignorespace (Ubuntu and Debian set ignoreboth by default), which is useful for commands that contain passwords.
Official documentation: Bash manual: history expansion.