By default, every command that you execute on your terminal is stored by the shell (command interpreter) in a certain file called a history file or shell command history. In Bash (the most popular shell on Linux systems), by default, the number of commands persisted in the history is 1000, and some Linux distributions have 500.
To check your history size in Bash, run this command:
$ echo $HISTSIZE
To see older commands that you have run, you can use the history command to display the shell command history:
Sometimes, you may want to disable the shell from logging commands to its command history. You can do it as follows.
Delete a Linux Command from History After Running
You can delete a command immediately from the shell history after running it on the command line by appending the
history -d $(history 1) command to it.
$(history 1) sub-command retrieves the latest entry in the history in the current terminal session, where 1 is the offset and the
-d option helps to delete it.
Any command run normally gets saved in the shell history.
$ echo "This command is saved in history" $ history | tail
However, when you append the
history -d $(history 1) command to a command line, it straight away gets deleted from the shell history as shown in the following screenshot:
$ echo "This command is not saved in history";history -d $(history 1) $ history | tail
Another way to prevent the shell from saving a command in history is to prefix the command with a space. But this depends fully on the value of the
$HISTCONTROL shell variable defined in the ~/.bashrc Bash startup file. It should be set to have one of these values: ignorespace or ignoreboth, for this method to work.
You can check the value of the
$HISTCONTROL variable as shown.
$ echo $HISTCONTROL OR $ cat ~/.bashrc | grep $HISTCONTROL
If the aforementioned shell variable is set, then any command prefixed with a space is not saved in the history:
$ echo "This command is not prefixed with space, it will be saved in history!" $ echo "This command is prefixed with space, it will not be saved in history!"
Here are some other interesting articles about the Bash history and history commands:
- 2 Ways to Re-run Last Executed Commands in Linux
- How to Clear BASH Command Line History in Linux
- Set Date and Time for Each Command You Execute in Bash History
That’s it for now! Use the comment form below to share your thoughts with us concerning this topic. Until next time, stay with us.