When you are working with terminal for long time, you need some of commands repeatedly. It would be easier if you can view the history of previously used command on your command line. In this article, we will discuss about history command, using that you can view the previously executed commands.
Use the history Command
history command is built-in command and it might work differently from shell to shell. In this article we will discuss about Bash built-in version of history command.
If you run the
history command without any options, it will show the whole history list with line numbers.
... 788 uptime 789 lscpu 790 exit 791 history
To execute the command from the list, use
!n command where
n is the line number of the list. From above output, to execute command on line number
788, you would type:
The output of history command does not fit to screen so you can make page wise output using less command:
history | less
Also, you can show last
n number of line by passing number as an argument with
history command. For instance, to view last
10 lines from history, type:
You should use the
down arrow key to navigate to the lines. Press
Enter key when you are on specific line to execute that command.
To execute the previously used command, type:
It’s very useful when you need to run commands with sudo privileges. You can just use
!! instead of typing whole command:
!-1 is equivalent to
!! and if you want to run the second last you can run
!-2, and so on.
To filter the output, use grep command. For example, you need to find commands which are run using
sudo word you would type:
767 sudo apt update
768 sudo apt upgrade
769 sudo reboot
796 history | grep sudo
Now, again you can run the
sudo apt update command, just type:
Save History Command List
Bash reads the history list from the
.bash_history file by default. In the current session the list of executed commands are kept in memory and once the session closed it saved to the file.
You can save the current session history list to the
.bash_history file using
-a option with history command.
To write the complete history list to the history file, use the
You also can clear the
history command list or specific part using the
history command. Use
-c option to clear entire history list:
To delete a specific line or lines between a start and end positions from the history list, use the
For example, to remove the lines between
745, you would type:
history -d 735 745
It will includes the both line numbers
745. You can pass single line number to delete a specific line.
The above command will clear the list only from the memory not from the
.bash_history file. To clear history from the file you should write the history list to the file:
In this article explained how to use
history command to get list of previously executed commands. To get more information about History Expansion, check the Bash manual.
If you have any questions or feedback, please leave a comment below.