Every Linux terminal allows you to view a history of its past commands using ‘history’ command. Terminal maintains a separate history file for each user in /home/username/.bash_history file. But sometimes you may need to save terminal history for future reference. In this article, we will learn how to backup & restore terminal history in Linux. You can use these steps on any Linux.
How to Save Terminal History in Linux
You can easily view the terminal history with either of the following commands. Replace username below with the username whose terminal history you want to view. Please note, you can view other users’ terminal history, only if you have the permission, such as root or admin, for it.
$ history OR $ cat /home/username/.bash_history
If you want to search for a specific command in terminal history, combine it with grep command as shown. Here is how to search for ls command in history.
$ history | grep 'ls' OR $ cat /home/username/.bash_history | grep 'ls'
Here are the steps to save terminal history in Linux.
1. Backup Terminal History
You can easily backup or save terminal history to another file, say, terminal_history with any of the following commands.
$ history > terminal_history OR $ cat /home/username/.bash_history > terminal_history
If you want to backup only specific commands from terminal history, then pass the output of above grep commands to the backup file.
$ history | grep 'ls' > terminal_history OR $ cat /home/username/.bash_history | grep 'ls' > terminal_history
Please note, the above commands will completely overwrite terminal_history file or create a new one if it doesn’t exist. If you want to append history to existing file use append ‘>>’ operator, instead of using > operator.
$ history | grep 'ls' >> terminal_history OR $ cat /home/username/.bash_history | grep 'ls' >> terminal_history
2. Restore Terminal History
If you want to restore terminal backup, use the following command to move or copy the contents of backup file to history. Replace username below with the user whose history file you want to restore.
$ mv terminal_history /home/username/.bash_history
After you have moved or copied the backup, you need to run the following command teo refresh history.
$ history -r
That’s it. In this short article, we have learnt how to backup & restore terminal history in Linux.
How to Delete All Instance of Character from String in Python
How to Randomly Select Item from Python List
How to Concatenate Strings in MySQL
What is Basename Command in Linux Shell
How to Compare Strings in Python