15 Examples To Master Linux Command Line History

Filed Under: Linux    59 Comments

 

Free eBook - Linux 101 Hacks. Get your copy now.

Bash Command Line ImageWhen you are using Linux command line frequently, using the history effectively can be a major productivity boost. In fact, once you have mastered the 15 examples that I’ve provided here, you’ll find using command line more enjoyable and fun.

1. Display timestamp using HISTTIMEFORMAT

Typically when you type history from command line, it displays the command# and the command. For auditing purpose, it may be beneficial to display the timepstamp along with the command as shown below.

# export HISTTIMEFORMAT='%F %T '
# history | more
1  2008-08-05 19:02:39 service network restart
2  2008-08-05 19:02:39 exit
3  2008-08-05 19:02:39 id
4  2008-08-05 19:02:39 cat /etc/redhat-release

2. Search the history using Control+R

I strongly believe, this may be your most frequently used feature of history. When you’ve already executed a very long command, you can simply search history using a keyword and re-execute the same command without having to type it fully. Press Control+R and type the keyword. In the following example, I searched for red, which displayed the previous command “cat /etc/redhat-release” in the history that contained the word red.

# [Press Ctrl+R from the command prompt,
which will display the reverse-i-search prompt]
(reverse-i-search)`red': cat /etc/redhat-release
[Note: Press enter when you see your command,
which will execute the command from the history]
# cat /etc/redhat-release
Fedora release 9 (Sulphur)

Sometimes you want to edit a command from history before executing it. For e.g. you can search for httpd, which will display service httpd stop from the command history, select this command and change the stop to start and re-execute it again as shown below.


# [Press Ctrl+R from the command prompt,
which will display the reverse-i-search prompt]
(reverse-i-search)`httpd': service httpd stop
[Note: Press either left arrow or right arrow key when you see your
command, which will display the command for you to edit, before executing it]
# service httpd start

3. Repeat previous command quickly using 4 different methods

Sometime you may end up repeating the previous commands for various reasons. Following are the 4 different ways to repeat the last executed command.

  1. Use the up arrow to view the previous command and press enter to execute it.
  2. Type !! and press enter from the command line
  3. Type !-1 and press enter from the command line.
  4. Press Control+P will display the previous command, press enter to execute it

4. Execute a specific command from history

In the following example, If you want to repeat the command #4, you can do !4 as shown below.

# history | more
1  service network restart
2  exit
3  id
4  cat /etc/redhat-release

# !4
cat /etc/redhat-release
Fedora release 9 (Sulphur)

5. Execute previous command that starts with a specific word

Type ! followed by the starting few letters of the command that you would like to re-execute. In the following example, typing !ps and enter, executed the previous command starting with ps, which is ‘ps aux | grep yp’.

# !ps
ps aux | grep yp
root     16947  0.0  0.1  36516  1264 ?        Sl   13:10   0:00 ypbind
root     17503  0.0  0.0   4124   740 pts/0    S+   19:19   0:00 grep yp

6. Control the total number of lines in the history using HISTSIZE

Append the following two lines to the .bash_profile and relogin to the bash shell again to see the change. In this example, only 450 command will be stored in the bash history.

# vi ~/.bash_profile
HISTSIZE=450
HISTFILESIZE=450

7. Change the history file name using HISTFILE

By default, history is stored in ~/.bash_history file. Add the following line to the .bash_profile and relogin to the bash shell, to store the history command in .commandline_warrior file instead of .bash_history file. I’m yet to figure out a practical use for this. I can see this getting used when you want to track commands executed from different terminals using different history file name.

# vi ~/.bash_profile
HISTFILE=/root/.commandline_warrior

If you have a good reason to change the name of the history file, please share it with me, as I’m interested in finding out how you are using this feature.

8. Eliminate the continuous repeated entry from history using HISTCONTROL

In the following example pwd was typed three times, when you do history, you can see all the 3 continuous occurrences of it. To eliminate duplicates, set HISTCONTROL to ignoredups as shown below.

# pwd
# pwd
# pwd
# history | tail -4
44  pwd
45  pwd
46  pwd [Note that there are three pwd commands in history, after
executing pwd 3 times as shown above]
47  history | tail -4

# export HISTCONTROL=ignoredups
# pwd
# pwd
# pwd
# history | tail -3
56  export HISTCONTROL=ignoredups
57  pwd [Note that there is only one pwd command in the history, even after
executing pwd 3 times as shown above]
58  history | tail -4

9. Erase duplicates across the whole history using HISTCONTROL

The ignoredups shown above removes duplicates only if they are consecutive commands. To eliminate duplicates across the whole history, set the HISTCONTROL to erasedups as shown below.

# export HISTCONTROL=erasedups
# pwd
# service httpd stop
# history | tail -3
38  pwd
39  service httpd stop
40  history | tail -3

# ls -ltr
# service httpd stop
# history | tail -6
35  export HISTCONTROL=erasedups
36  pwd
37  history | tail -3
38  ls -ltr
39  service httpd stop
[Note that the previous service httpd stop after pwd got erased]
40  history | tail -6

10. Force history not to remember a particular command using HISTCONTROL

When you execute a command, you can instruct history to ignore the command by setting HISTCONTROL to ignorespace AND typing a space in front of the command as shown below. I can see lot of junior sysadmins getting excited about this, as they can hide a command from the history. It is good to understand how ignorespace works. But, as a best practice, don’t hide purposefully anything from history.

# export HISTCONTROL=ignorespace
# ls -ltr
# pwd
#  service httpd stop [Note that there is a space at the beginning of service,
to ignore this command from history]
# history | tail -3
67  ls -ltr
68  pwd
69  history | tail -3

11. Clear all the previous history using option -c

Sometime you may want to clear all the previous history, but want to keep the history moving forward.

# history -c

12. Subtitute words from history commands

When you are searching through history, you may want to execute a different command but use the same parameter from the command that you’ve just searched.

In the example below, the !!:$ next to the vi command gets the argument from the previous command to the current command.

# ls anaconda-ks.cfg
anaconda-ks.cfg
# vi !!:$
vi anaconda-ks.cfg

In the example below, the !^ next to the vi command gets the first argument from the previous command (i.e cp command) to the current command (i.e vi command).

# cp anaconda-ks.cfg anaconda-ks.cfg.bak
anaconda-ks.cfg
# vi  !^
vi anaconda-ks.cfg

13. Substitute a specific argument for a specific command.

In the example below, !cp:2 searches for the previous command in history that starts with cp and takes the second argument of cp and substitutes it for the ls -l command as shown below.

# cp ~/longname.txt /really/a/very/long/path/long-filename.txt
# ls -l !cp:2
ls -l /really/a/very/long/path/long-filename.txt

In the example below, !cp:$ searches for the previous command in history that starts with cp and takes the last argument (in this case, which is also the second argument as shown above) of cp and substitutes it for the ls -l command as shown below.

# ls -l !cp:$
ls -l /really/a/very/long/path/long-filename.txt

14. Disable the usage of history using HISTSIZE

If you want to disable history all together and don’t want bash shell to remember the commands you’ve typed, set the HISTSIZE to 0 as shown below.

# export HISTSIZE=0
# history
# [Note that history did not display anything]

15. Ignore specific commands from the history using HISTIGNORE

Sometimes you may not want to clutter your history with basic commands such as pwd and ls. Use HISTIGNORE to specify all the commands that you want to ignore from the history. Please note that adding ls to the HISTIGNORE ignores only ls and not ls -l. So, you have to provide the exact command that you would like to ignore from the history.

# export HISTIGNORE="pwd:ls:ls -ltr:"
# pwd
# ls
# ls -ltr
# service httpd stop

# history | tail -3
79  export HISTIGNORE="pwd:ls:ls -ltr:"
80  service httpd stop
81  history
[Note that history did not record pwd, ls and ls -ltr]

Recommended Reading

Bash Cookbook, by Carl Albing, JP Vossen and Cameron Newham. Bash is a very powerful shell. This book will help you to master the bash shell and become highly productive. Whether you are a sysadmin, DBA or a developer, you have to write shell script at some point. A wise sysadmin knows that once you’ve mastered the shell-scripting techniques, you can put your servers on auto-pilot mode by letting the shell-scripts do the grunt work. To get to the auto-pilot mode of sysadmin, you definitely need to master the examples provided in this cookbook. There are quiet few Bash shell books out there. But, this books tops them all by giving lot of detailed examples.
 
Additional Linux book recommendation: 12 Amazing and Essential Linux Books To Enrich Your Brain and Library
 





Tags: , , , , ,

59 Responses to “15 Examples To Master Linux Command Line History”

  1. hey, thanks. i actually learned a few things I didn’t know I could do before.

  2. Whoaah! Very useful! Thanks =)

  3. Cool tricks, will come definitely come in useful to me, bookmarked for reference.

  4. An observation:

    It’s not immediately clear from the title and introduction that this article applies to the bash shell. I realize that bash is the default shell and so practically synonymous with “the Linux command line”, but there are other shells that a user could end up in, particularly if using a minimal rescue environment. It might be helpful to explicitly mention bash up front so people don’t get confused if these tips don’t work properly. Or perhaps show some of the differences for common shells if there are any for a given example.
    Maybe even explaining briefly the difference between the ‘command line’ and a shell so people can learn what’s really going on.

    Great article though.

  5. @AurGlass,

    Thanks for the feedback. Like you’ve mentioned, I left it out because the default shell in Linux is bash. You brought-up a very valid point and I’ll keep that in mind for the future articles.

  6. The best reason I ever found to change the history file name using HISTFILE was described here:
    http://moonpup.blogspot.com/2007/11/keeping-separate-history-files-for.html
    whereby each administrator of a box gets his own superuser history.
    Hope that’s what you were looking for.

  7. great article, very handy.

    my new favourite feature of bash is using . to put the last argument of the previous command into your new command..something like this:

    mkdir some_dir_name
    cd .

    some_dir_name will appear on your cd line.

  8. Use histfile when you automount a common home directory and you want separate history files for each host that you log into.

    export HISTFILE=~.bash_history.d/$HOSTNAME

  9. I find the !$ syntax for the last argument of the previous command quicker to type than !!:$ mentioned in 12. Likewise using !:1, !:2 for the previous arguments (starting with !:0 as the first).

  10. very useful article, thank you very much

  11. Great Article, thank you. Lots of stuff I didn’t know before, very helpful!

  12. heh..my esc key was eaten in my above comment. that should read esc .

    not just .

  13. @frankb, @ta,

    Thanks for sharing the reasons to use HISTFILE with examples.

    @miker,

    “esc .” is definitely a great use to substitute the argument from the previous command to the current command. Thanks for the tip.

    @pwc101,

    I agree, the argument number is probably easier to use. Thanks for the feedback.

  14. I’m a huge fan of timestamped history. Comes in handy when you’re trying to prove your client bricked his Linux server. :)

  15. Great tips Ramesh. I didn’t find any excuse for not digging it :)

    Cheers,
    Ajith

  16. you can also use !$ instead of !!:$ to retreive the last argument from the last command

    mkdir -p really/deep/directory/tree
    cd !$

    will get you into really/deep/directory/tree

  17. For No 12, Alt+. (Alt+ dot ) is much faster.

  18. Hello Ramesh,

    Excellent post!

    I never knew about all this before.

    Thank you so much for enlightening us.

    Do keep writing.

    Zaheer.

  19. #12 Can be shortened to !$ which is a bit faster.

  20. Ctrl-R. New favorite! Thanks. -j

  21. very good…thanks a lot

  22. Very informative post!
    Thanks

  23. @dethmetaljeff, bash, miker, anon,

    Thanks for pointing out the alternative for example#12. i.e instead of !!:$, following can also be used to substitute the previous argument.

    1. vi !!:$
    2. vi !$
    3. vi Alt-key + .
    4. vi Esc-key + .

  24. The most comprehensive tutorial I have found on the history command I have found so far.

    Nice work! Thank you.

  25. wow……..great list dude……..thanks for sharing ……..

  26. Hi, I like I lot but some how on my RedHat Linux kernel.com 2.4.20-8 #1 Thu Mar 13 17:54:28 EST 2003 i686 i686 i386 GNU/Linux
    command given doesn’t work:
    export HISTTIMEFORMAT=’%F %T ‘
    I am running bash as following output said:
    [root@kernel root]# echo $SHELL
    /bin/bash
    Any ideas?
    Thx
    Christian

  27. Simply great. It will be of great help in my day- to – day development work at office.

  28. It is an excellent article. These tricks helps me a lot in making commandline usage more interesting and smooth. Thanks

  29. What a nice list. Thanks!

  30. Excellent Post

  31. Hi

    This article very is usefull, in fact more informative. I need a help from you all that I want the history command shoud shows the command with date:time:servername:userid:user’s hostname or ip:command for monitoring purpose.

    At the same time, I have to capture in a file what are the command entered by user then the file redirect to some where.

    Your help is more appreciated in this regards. This is going to be implemented in red hat linux

    regards
    sharmila

  32. Hi,

    Really great tips yaar….. I did not know in detail that history of commands work like this… Thanks alot and kindly post articles like above..which will educate geeks like me….

  33. Hi sharmila..

    I am a system administrator in an insurance company working on RHEL. What bout you? I am presently trying Ubuntu8.1 desktop version..really its a great os.

  34. This article is very good,you are given very good explanation for History command in Linux, it’s very useful

  35. Hi,
    > # export HISTTIMEFORMAT=’%F %T ‘
    > # history | more
    > 1 2008-08-05 19:02:39 service network restart
    > 2 2008-08-05 19:02:39 exit
    Is there any possibility to see history in this format without “export HISTTIMEFORMAT=’%F %T “.
    If no — How I can delete (clear) ’%F %T ‘ from HISTTIMEFORMAT ?
    Thanks!

  36. Great website, great article, awesome comments section.

  37. Hi!

    This is a very extensive and useful description. I worked on AIX many years ago. There was a method, with I could handle the history in vi mode. I don’t remember exactly. Maybe there was a prerequisite setting: the EDITOR environment variable?
    And, I could enter in the vi mode with with ESC+K .

    Now I’m using RHEL, and I’m searching about that, if it’s working in Linux too.

    regards

    Tom

  38. Hi!

    I’am again. I’ve found it:

    set -o vi

    And entring in vi mode is just with the ESC.

    Tom

  39. Great article!!!
    This page went straight away into my favorites…
    I was looking for a shortcut like Ctrl-R , but this did not work for me. one friend suggested used of Alt-P instead and I use it extensively…

  40. Hi All,

    Any one can help me on linux
    1. How to check the 2 or 3 week log in log with time and date.
    * i already try lot of command from this forum andmany other forum.

    Please help me !!!!!!!!!

  41. Thanks for the post

    i do found
    HISTTIMEFORMAT,
    HISTIGNORE,
    HISTSIZE as useful in multi user environment..

    HISTTIMEFORMAT will be useful when there is disaster to trackdown
    the time which can be comparable with the service down email notification

  42. @Jean-Luc Lacroix, Roshan, Nihar, Muthu, DavidTan, Velusamy, Ramesh, Nagaraju,

    Thanks a lot for your comment. I’m very happy that you found this article useful.
     
    @Maxwell,

    Yeah. The comment section on this article is very engaging and I’m very greatful to all those who commented on this article.
     
    I’m hoping that everybody who reads this comment section would take some time to leave a response.
     

    @Christian,

    I tried that on Red Hat Linux and it works without any problem. I tried on 2.6 kernel. But, I don’t think that is the issue for you.
    Can you make sure that you type the following command, instead of copy/paste. Sometimes, copy/paste may do some weird things.

    $ export HISTTIMEFORMAT=' %F %T';
    

     
    @Strang,
    Why would you want to display the history in that format without using HISTTIMEFORMAT? Can you please provide little bit more details on what you are looking for?
     

    @Tom,
    Thanks for following up on this comment section with an answer to your own question.

     

    @Parag,
    mm.. I wonder why Ctrl-R didn’t work for you. Is Ctrl-[character] combination somehow disabled on your system. Anyway, I’m glad you found the Alt-P helpful instead.
     

    @Thiru,
    What log are you trying to look for? Can you explain little bit more in detail on what exactly you are trying to achieve?
     

    @Srinivas,
    Yeah. Once you start using HISTTIMEFORMAT and HISTIGNORE, you will wonder, how you’ve used Linux command-line for so long without using this feature.

  43. I may require the argument of nth cmd instead of previous command…
    How can i get it ?

  44. Excellent as you can tell from the ongoing positive feedback
    -yak

  45. @Sourabh,

      3  ls /etc/sysctl.conf
      4  export HISTTIMEFORMAT='%F %T';
      5  uname -a
    

     
    Let us say in the above example, you want to take the argument of history command#3 (which is ls /etc/sysctl.conf) and use it. You can do that as shown below.

    $ cat !3:$
    [Note: This is equivalent to "cat /etc/sysctl.conf" ]
    

     
    @yakupm,
    Thanks for your comment. I’m very glad that you found this article helpful.

Discussion Area - Leave a Comment





Enter your email address:

RSS
RSS Subscribe

Sponsors


Password Dragon


Free e-Book


Download Free eBook
Linux 101 Hacks Book
"These useful hacks are concise, well written and easy to read. Well done - I will recommend this eBook to my students."

Prof. Dr. Fritz Mehner
(Author of several Vim plugins)

Categories


pointer Linux pointer Database
pointer Hardware pointer Security
pointer Productivity pointer Java
pointer Software pointer Windows
pointer General



Popular Posts



12 Amazing Linux Books


  • 1. Sed and Awk
  • 2. Learning the Vi and Vim Editors
  • 3. Bash Cookbook
  • 4. SSH, The Secure Shell
  • 5. Essential System Administration
  • 6. Linux Server Hacks, Volume One
  • 7. DNS and BIND
  • 8. Understanding the Linux Kernel
  • 9. Linux Cookbook
  • 10. Linux Firewalls
  • 11. Linux Administration Handbook
  • 12. Beginning Ubuntu Linux
  • Read full review of these 12 books

Community
About TheGeekStuff
Ramesh

My name is Ramesh Natarajan. I will be posting instruction guides, how-to, troubleshooting tips and tricks on Linux, database, hardware, security and web. My focus is to write articles that will either teach you or help you resolve a problem. Read more