Linux Command Line History
Learn how to view, search, repeat, edit, configure, and safely clear command history in Bash and other Linux shells.
Shell history is the recorded list of commands entered in an interactive shell, meaning a shell session used directly by a person at a terminal. It helps you avoid repeated typing, recover long commands, and review how a task was performed.
History is maintained separately for each shell and user account. A Bash session for one user does not automatically share its in-memory history with another user or with every other shell. Bash, Zsh, Fish, and other shells provide similar features, but their commands, settings, and storage behavior differ. The examples in this lesson primarily use Bash.
Displaying Previous Commands
In Bash, the history builtin displays entries recorded by the current shell. A builtin is a command supplied by the shell itself rather than a separate executable.
historyTypical output includes an event number, which is the numeric identifier assigned to each history entry, followed by the command:
15 pwd
16 ls -la
17 find . -type f -name '*.log'Event numbers can be used as references for history expansion. They are not universal constants: the visible numbering depends on the current session and its retained history.
To display only a chosen number of recent entries, give history a number:
history 20This shows the latest 20 entries available to the current shell. The number displayed and the number retained are configurable in Bash, so another machine or account may show a different amount.
Repeating Commands with History Expansion
History expansion is shell syntax that substitutes a previous command before the shell executes the resulting command. In Bash, an event number can be selected with an exclamation mark:
!17If event 17 is the desired command, Bash expands !17 to that command and then executes it. The immediately previous command can be repeated with:
!!!! executes immediately, so use it carefully, especially after commands that change files, permissions, or system configuration. For a safer review, press the Up Arrow to place the previous command on the editable command line, inspect it, and press Enter only when it is correct.
Bash can also show an expansion without executing the expanded command:
history -p '!!'
history -p '!17'The single quotes prevent the current command line from expanding the exclamation mark before the history builtin receives it. History expansion rules vary among shells; an exclamation mark may also have special meaning in Bash, depending on settings and quoting.
Keyboard Navigation and Editing
In Bash's usual Readline editing mode, the Up Arrow recalls older commands and the Down Arrow moves toward newer commands. Readline is the line-editing library that provides these common Bash keyboard bindings.
- Press the Up Arrow to recall a previous command.
- Edit its command name, option, argument, or path.
- Review the complete line.
- Press Enter to execute the edited command, or use another key to continue editing.
# Previously entered:
find /var/log -type f
# Recall it, edit /var/log to /tmp, then execute:
find /tmp -type fNavigation only recalls a command; it does not execute it. Execution occurs when you press Enter. This makes arrow-key recall safer than blindly using !! when you need to change an argument.
Reverse History Search
Reverse-i-search is an incremental search backward through command history. In a typical Bash terminal, press Ctrl+R:
(reverse-i-search)`':Type a distinctive fragment, such as dd or systemctl. Bash displays the newest matching command as you type:
(reverse-i-search)`dd': sudo dd if=image.iso of=/dev/sdb status=progressPress Ctrl+R again to move to an older command containing the same text. Common ways to finish the search are:
- Enter: execute the selected command immediately.
- Right Arrow or Up Arrow: accept the result onto the command line so you can inspect or edit it before execution.
- Ctrl+C: cancel the search and return to an empty prompt.
- Ctrl+G: cancel the search in many Readline configurations.
- Ctrl+R repeatedly: continue searching older matching entries.
Some Readline configurations also provide forward search with Ctrl+S, but terminal flow-control settings can intercept that key. Reverse search is usually the most useful starting point.
Common Command-History Actions
| Task | Command or key binding | What it does | Safety note |
|---|---|---|---|
| Show history | history | Lists recorded entries and event numbers. | Review output for secrets before sharing it. |
| Show a limited number of entries | history 20 | Shows the latest 20 available entries. | The result depends on retained session history. |
| Run a numbered entry | !17 | Expands and executes event 17. | Verify the number and expanded command first. |
| Run the previous entry | !! | Immediately executes the previous command. | Do not use blindly for destructive commands. |
| Navigate backward and forward | Up Arrow and Down Arrow | Recalls commands for review and editing. | Pressing Enter executes the current line. |
| Reverse search | Ctrl+R | Finds older commands containing a typed substring. | Inspect the selected command before pressing Enter. |
| Clear current history | history -c | Removes entries from the current Bash session's memory. | It does not necessarily remove the persistent history file. |
Clearing Command History
In Bash, this command clears the current shell's in-memory history list:
history -cIn-memory history and persistent history are different:
- Session history: entries currently held by the running shell.
- Persistent history: entries saved in the shell's history file for later sessions.
If an old entry remains in the history file, clearing memory alone may not remove it permanently. Bash can write the current list to its history file with:
history -wAfter clearing the current list, history -w commonly writes the now-empty list and truncates the file according to the shell's behavior. File removal may also be necessary in a controlled cleanup, but deleting a file while other shells are running can be ineffective: another shell may later write its older in-memory entries back.
History cleanup should therefore account for all active sessions and both storage locations. Clearing history also removes useful troubleshooting and audit context, so do it deliberately rather than as routine maintenance.
Persistent History and Bash Configuration
A Bash history file is a file used to retain command history across sessions. The HISTFILE variable identifies its location. A common setup uses a file in the user's home directory, but the exact path is configurable.
| Variable or option | Purpose | Example setting | Persistence considerations |
|---|---|---|---|
HISTFILE | Identifies the persistent history file. | HISTFILE="$HOME/.bash_history" | Put the setting in a Bash startup file to affect future interactive sessions. |
HISTSIZE | Controls the approximate number of entries retained in memory. | HISTSIZE=5000 | Affects new or running sessions after the variable is assigned. |
HISTFILESIZE | Controls the approximate maximum number of entries saved in the file. | HISTFILESIZE=10000 | File trimming occurs according to Bash's write behavior. |
HISTCONTROL | Filters duplicates and commands beginning with a space. | HISTCONTROL=ignoredups:ignorespace | Set it in a startup file if the policy should apply to future sessions. |
HISTIGNORE | Uses patterns to omit selected commands. | HISTIGNORE='ls:pwd:history' | Patterns are not a security boundary and can be incomplete. |
HISTTIMEFORMAT | Formats timestamps shown by the history builtin. | HISTTIMEFORMAT='%F %T ' | It changes display formatting; it does not make history tamper-proof. |
histappend shell option | Appends history instead of replacing the file when Bash exits. | shopt -s histappend | Useful for multiple terminals, but append alone does not synchronize every session immediately. |
You can inspect current Bash settings with commands such as:
printf '%s\n' "$HISTFILE" "$HISTSIZE" "$HISTFILESIZE"
printf '%s\n' "$HISTCONTROL" "$HISTIGNORE" "$HISTTIMEFORMAT"
shopt histappendTo configure common behavior for future interactive Bash sessions, place suitable lines in a Bash startup file used by your account:
HISTSIZE=5000
HISTFILESIZE=10000
HISTCONTROL=ignoredups:ignorespace
HISTIGNORE='ls:pwd:history'
HISTTIMEFORMAT='%F %T '
shopt -s histappendStartup-file names and loading rules depend on how Bash is invoked. Make a change in the appropriate interactive-shell configuration file, then start a new terminal or reload the file carefully.
Multiple Terminals
Each interactive Bash session normally has its own in-memory list. A traditional setup may write history when a shell exits, so one terminal may not see commands entered in another terminal until later. Concurrent shells can also overwrite one another's file updates.
Bash provides explicit operations for managing this:
history -a # append this session's new entries to the file
history -n # read entries added by other sessions into this shell
history -w # write the current in-memory list to the file
shopt -s histappendA prompt hook can automate history -a and history -n, but frequent synchronization introduces trade-offs such as duplicate entries, ordering differences, and more file writes. Test any multi-terminal configuration before relying on it.
Privacy and Sensitive Commands
Command history is not secure storage. A command containing a password, API token, private path, or confidential argument can remain in the in-memory history list, the history file, terminal scrollback, logs, backups, or process-inspection output while the command is running.
Prefer safer workflows:
- Use a program's hidden password prompt rather than placing the password in an argument.
- Use a protected input file with restrictive permissions when the tool supports it.
- Use environment handling appropriate to the specific tool, remembering that environment variables may also be observable by processes with suitable access.
- Use a secret manager or credential facility when available.
- Avoid putting secrets directly in command arguments whenever possible.
Bash can omit commands that begin with a space:
HISTCONTROL=ignorespace
secret-tool lookup service exampleBash can also omit consecutive duplicates:
HISTCONTROL=ignoredupsThese controls have important limitations. They are Bash-specific, depend on exact input and configuration, do not erase a command already saved elsewhere, and do not protect secrets from other observation mechanisms. HISTIGNORE patterns can help filter routine commands, but they are not a reliable secret-protection system.
If a secret was entered on a command line, treat it as exposed when appropriate: revoke or rotate the credential, remove the entry from session and persistent history, check other copies such as logs and backups, and change the workflow for future use.
Troubleshooting History Problems
A command expected in history is missing
- It may have been entered in another shell, user account, or shell type.
- The current session may not have written its in-memory entries to the history file.
HISTCONTROLorHISTIGNOREmay have filtered it.- The command may have run non-interactively; non-interactive commands are not normally recorded as interactive history.
Check the active shell, inspect history variables, and use history -a or history -w when appropriate.
Commands from another terminal do not appear
Separate sessions keep separate in-memory lists, and Bash may write only when a shell exits. Enable histappend and use history -a and history -n where immediate sharing is useful. Expect possible ordering and duplication trade-offs.
history -c did not remove an older command permanently
The persistent history file may still contain the entry, or another open shell may write its older memory back later. Manage both the current session and the persistent file, and coordinate active shells before performing sensitive cleanup.
Ctrl+R does not work as expected
The terminal or an application may intercept the shortcut, the shell may use different key bindings, or no command may match the search text. Confirm the active shell, try a distinctive fragment, inspect that shell's key-binding documentation, and use history plus arrow-key navigation as a fallback.
An exclamation-mark command has an unexpected result
The event number may not exist in the current session, or punctuation may have been interpreted by history expansion. Run history to verify the number, use history -p to inspect an expansion, or recall the command with the Up Arrow and edit it before execution.
Exam-Relevant Notes
- History builtin: a shell-provided command for displaying and managing history entries.
- Event number: the numeric identifier beside a history entry.
!number: executes the command identified by that event number in shells that support this expansion.!!: immediately repeats the previous history entry in Bash.- Up Arrow: recalls a command for possible editing; it does not execute it by itself.
Ctrl+R: starts reverse incremental search in typical Readline-enabled Bash sessions.history -c: clears the current Bash session's in-memory history, not necessarily every persistent copy.HISTSIZEversusHISTFILESIZE: the first concerns in-memory entries; the second concerns the saved history file.- Security: history should never be treated as secure storage for passwords or tokens.
Next Steps
For related skills, see Linux topics, Bourne Again Shell (Bash), and showing the full path of shell commands.