The history command in Linux displays the list of previously executed commands in a tabular format; with the first column displaying the number of commands, and the second column displaying the actual commands that were executed.
The list of previously typed commands can also be accessed by pressing the ‘Up’ and ‘Down’ arrow keys on the keyboard, so as to avoid typing a recently executed command again.
Bash stores command history in a file typically located at ~/.bash_history
, each command is appended to this file when executed, and the history is loaded into memory when a new shell session is started.
Find All Executed Commands in History
To find all previously executed commands along with their corresponding line numbers, use:
history
There can be cases when a user has typed a command that may expose sensitive information, such as a password, in the command history. It is unsafe to keep such a command in history, as it exposes it to anyone who can access the command history.
Let us see how to delete such commands from history.
Remove a Specific Command in History
The simplest method to remove a command from history is by using the history command itself along with the -d
option followed by the command number.
history -d <command_number>
For example, to remove the command with line number 10, type.
history -d 10
Remove a Range of Commands in History
To remove a range of commands, specify the starting and ending line numbers separated by a space.
history -d 10 15
Clear All History Commands
If you want to clear your entire command history, you can use the history command with the -c
option, which will clears the history list by deleting all the entries.
history -c history
Another approach involves directly editing the ~/.bash_history
file and manually delete the command entry.
nano ~/.bash_history
Locate and delete the line containing the command you want to remove, then save and exit Nano.
Controlling History Size
Bash allows you to specify the maximum number of commands to keep in history using the HISTSIZE variable. By setting HISTSIZE to a lower value, you can automatically remove older commands from history as new ones are added.
export HISTSIZE=1000
This sets the maximum history size to 1000 commands.
Conclusion
In this article, we discussed the history command and how to delete certain commands or all the commands from the history. The history is stored in a file called ‘.bash_history’ which is present in the user’s home folder.
For more information on the history command, refer to the man page of history by executing:
man history
If you have any questions or feedback, make sure you leave a comment below!