How to use History Command in Linux Bash
History is very useful command. More than 90% of time, Linux users type same commands again and again. To improve the efficiency and output as a Linux user, one should be really familiar with History.
How to Use History Command
Just type history on your bash command prompt. If you have been using your shell for a while, you will see lot of commands.
history
Just to see last 10 commands do following...
history | tail -10
If you want to scroll through all the commands, just do
history | less
And then you can scroll through the less editor by pressing key j for going down and k for going up. If you want to search through history in the less editor, just type forward / and then type the keyword you want to search for
If you look at the history, you will see a command number in front of every command
865 echo "hello"
866 history | tail -4
867 echo "hello world"
868 ls -lrt
869 echo "hello testing"
870 history | tail -4
871 find / | egrep test.py
872 history | tail -10
873 echo "testing"
874 history | tail -10
How to execute previous command using !
lets say we want to execute the command 870, instead of typing the whole command just type
!870
If you just want to run the last command then do double !!
!!
Saving the history
Every time you open a new shell, only the history of that shell is saved. If you want to append to history, the just do
history -a
Above will save history to file .bash_history
If for some reason you want to save the history to new file, you can simply use the pip command too.
history > history.txt
Clearing the history
You can also create the history and start from the blank slate by using -c switch
history -c
Delete the history between lines
We can also delete history specifically by using switch -d
history -d 869 874
Above will delete the history between line 869 and 874
Customize history size
We can also customize how many lines should be stored by history. By setting variable HISTSIZE
Modifying History Size
HISTSIZE=10000
Above setting will make sure latest 10000 commands will be saved in bash history.