Tuesday, June 14, 2011

bash history

I use the history command in Linux quite a bit, but I don't really use it to its full potential. Most of the time, I'm simply typing the following to get a list of the commands in my BASH history:

$ history

That produces a numbered list of commands. Here are the last three lines of my output:

  203  man man
  204  exit
  205  history

Then I can use  "!(n)" to run the nth command, like this:

$ !203

Or else I'm using the "up" or "down" arrows to scroll through the commands in history, then pressing "Enter" to run a command.

Sometimes it's useful to see the actual text file where the history is stored. In PCLinuxOS, that file is ~/.bash_history.

When you're at a root prompt, typing history will show a list of commands that you've run as root, but not the list of commands you've run as a normal user, because the normal user's history and root's history are stored in different files. In PCLinuxOS, root's bash history is stored at /root/.bash_history. You'll need to have root access to even view the file.

There's tons of info out there on this topic, but here are a few good links:





More information can be found hidden deep inside man bash, including the "Event Designators" section under the "History Expansion" heading:

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

       !      Start  a history substitution, except when followed by a blank, newline, carriage
              return, = or ( (when  the  extglob  shell  option  is  enabled  using  the  shopt
       !n     Refer to command line n.
       !-n    Refer to the current command line minus n.
       !!     Refer to the previous command.  This is a synonym for `!-1'.
              Refer to the most recent command starting with string.
              Refer  to the most recent command containing string.  The trailing ? may be omit‐
              ted if string is followed immediately by a newline.
              Quick substitution.  Repeat the last command,  replacing  string1  with  string2.
              Equivalent to ``!!:s/string1/string2/'' (see Modifiers below).
       !#     The entire command line typed so far.

No comments: