Introduction
The GNU history library keeps track of all the commands that run on the system in the ~/.bash_history file by default. You can use this history to see and recall the past commands.
In case you have security concerns, you can also clear this history. In this article, you will learn how you can view, manipulate and delete the terminal history in ubuntu.
The commands in this tutorial are executed on the ubuntu 20.04 system.
How to View Terminal History in Ubuntu
View all past commands in the History
You can display the previous history through the following command.
history
View last ‘n’ number of commands in the History
You can also narrow down the history display to a specific number of lines. For example, to display the most recent 5 commands, run the following command.
history 5
How to Delete Terminal History in Ubuntu
Delete All Previous Commands in History
Run the following command to delete the current terminal history.
history -c
You can notice that the above command will only delete the current terminal history. It will not affect the previous history that is stored in the history file. To overwrite the whole history file, you need to run the following command after running the “history -c” command
history -w
You can notice that the previous history has been deleted and overwritten in the following outcome.
Delete Single Command in History
You can delete specific lines in the history with the following command.
history -d <<line number>>
Note: Insert the line number of the command you want to delete in the above command. You can see the line number displayed with the command while viewing the history.
Delete History by Clearing ~/.bash_history File
You can clear the entire terminal history with the following command.
ln -sf /dev/null ~/.bash_history && history -c
This command will link the /dev/null file to the history file and delete the records.
Delete History by Disabling the Terminal/Bash History Logging
To turn off the logging of the terminal command, run the following commands.
sudo sh -c "echo "unset HISTFILE" >> /etc/profile"
Note: you will need sudo/root privilege to execute the above command.
Delete History by Editing the .bashrc File
You can change HISTSIZE and HISTFILESIZE variables in the .bashrc file to stop the history logging. To do that open a .bashrc file with the following command.
nano .bashrc
Now go to the lines mentioning HISTSIZE and HISTFILESIZE and change their value to zero. Press Ctrl+O and Ctrl+X to save changes and exit.
Conclusion
Terminal history can be a benefit in case you want to revisit/recall the past commands. But it can be a security risk because they can show system tools, configurations, and settings. You can view/preserve or delete terminal history with the help of this article.