Bash History | History Command in Linux | How to Use History Command | Search in History

Bash History Command
Bash History

History is shell command to print all previous executed command on the terminal. its daily used by system admin to get info about command executed by user.



History Command Syntax:

     history
     history [n]
     history -c
     history -d offset
     history [-anrw] [filename]
     history -ps arg

To Print all history
history
Print all history, history command

To print last number of history command
history [n]
history  5
history print number of commnad

To grep command from history
history | grep cat
grep command from history

To remove any command from the History

We will use history command with -d option and history number,
history -d 11

delete any command from shell history


To Search Command

To Search previously executed command by pressing  "Ctrl+r" from the Keyboard, Type the command, Once you’ve found the command you’re looking for, press "Enter" to execute the same else press "esc" to cancel it.

search command in history

To write all history command in file
history -w <filename>
history -w /tmp/test.history
write all history command in file

Event Designators

An event designator is a reference to a command line entry in the history list.

!n  = Refer to command line number, for the example we want to print 40 number of command so we will use  below command, we can also use "!-n"   Refer to the command n lines back.
!40
history event designators

!string   = Refer to the most of recent command starting with string
!hostname


!!           =  Refer to the previous command, it will print last executed command, for example we print hostname and !! in the terminal, !-1 is the same as !! and executes the last command from the history list, !-2 second to last, and so on.
!!



History Configuration

We can configure history by using following command temporary, we can also  add all variable in bashrc for permanents 

To  History Size :  by default bash keeps 500 lines command in history list, we can resize with HISTSIZE environment variables

export HISTSIZE=10000

To control history with HISTCONTROL variable

ignorespace - commands that start with space are not saved in the history list.
ignoredups - duplicate commands are not saved.
export HISTCONTROL=ignorespace
export HISTCONTROL=ignoredups
To add timestamp in history
export HISTTIMEFORMAT="%F %T: "

To append history in ~/.bash_history. when you exit a shell
shopt -s histappend

To Clear all bash history
history -c

Thanks,


No comments

Powered by Blogger.