How to Run a Linux Command Without Saving It in History

How to Run a Linux Command Without Saving It in History

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
Check Linux History Size
Check Linux History Size

To see older commands that you have run, you can use the history command to display the shell command history:

$ history
Check Linux Commands History
Check Linux Commands 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.

The $(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
View Linux Commands History
View Linux Commands History

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
Delete Linux Command History After Running
Delete Linux Command History After Running

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
Check HISTCONTROL Variable
Check HISTCONTROL Variable

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!"
Don't Save Linux Command in History
Don’t Save Linux Command in 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.


Comments are closed.