25 January 2012

Play with history Command in Linux/Unix

3 comments

history command shows the list of commands you had executed in your terminal. This command is useful when you want to execute same command again and again , in that case you can recall that command and save your precious time. Here are some examples of history command

1. Simply Display history of my commands
$ history

1  ls
2  reset
3  cat abc.lst
4  reset
5  cat abc.lst xyz.lst

Note: View command history page by page using following command
$ history|more

1  ls
2  reset
3  cat abc.lst
4  reset
5  cat abc.lst xyz.lst
6  reset
7  cat > pqr.lst
8  cat pqr.lst

2. !! : Run the last command that you ran.
$ ls
abc.lst   def.lst   examples.desktop   js

$ !!
ls
abc.lst  def.lst  examples.desktop  js 

3. !n : Re-run the nth command in history.
$ history|more

502  ls
503  history|more
504  history
505  reset
506  history|more
507  ls
508  reset
509  ls
510  reset
511  ls
512  reset
513  history
514  cat abc.lst
515  history|more

$ !509
ls
abc.lst  def.lst  examples.desktop  js 

4. !-n : Refers to the nth command from the end of the history list.
$ history|more

518 ls                
519 reset
520 history|more

$ !-3
ls
abc.lst   def.lst   examples.desktop   js

5. !str : Execute previous executed command that starts with str.
$ history | grep cat

30  cat -b cut1
33  cat -s cut1
36  cat -s /etc/passwd
94  cat file1
105  cat file2
110  cat file1
118  cat file1
122  cat > file1
124  cat file1
126  cat > file2 file3 file4
131  cat > file1 file2 file3
182  cat > sandeep2.lst
227  cat file1
229  cat file2
324  cat /etc/hosts
514  cat abc.lst
528  cat abc.lst
529  history | grep cat

$ !cat
cat abc.lst
my name is xyz
iam a good boy

Note: cat abc.lst was most recently executed command.

How to Remove history list

1.To remove complete history list use
$ history -c

2. To remove particular line from history list.
$ history

8 history
9 ls
10 history
11 cd ..
12 cd
13 history

$ history -d  11       [This  remove 11th command from history list]

$ history

8 history
9 ls
10 history
11 cd
12 history
13 history -d 11
14 history

Four different ways to repeat your previous command

There are four different ways to repeat your previous command . These are

1. Use Up arrow to view and press enter to execute it.
2. Type !! and press enter to execute it.
3. Ctrl + p and press enter to execute it.
4. !-1 and press enter to execute it.

How to increase the size of .bash_history file


Step 1: Check the size of your .bash_history file
$ echo $HISTSIZE
500

Step 2: By default .bash_history file stores only 500 entries , you might want to increase it for some reason , you can do it by modifying ~/.bashrc file , add following line in ~/.bashrc file
export HISTSIZE=1000

Step 3: Logout and Login again and now check your history size
$ echo $HISTSIZE
1000

That's it.
Hope you Enjoyed the post :).


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

3 comments: