Thursday, August 22, 2013

Bash shell history commands

Some handy tips while working with bash history on linux.

The basics, defining the history file:

$ export HISTFILE = ~/.bash_history

Disabling history for your session:

$ export HISTSIZE=0

HISTSIZE affects the in-memory store, to set how many lines the file can contain we use HISTFILESIZE.

Adding a time stamp on the history list:

$ export HISTTIMEFORMAT='[%F %T]  '

History will look like this:

    1  [2013-06-09 10:40:12]   cat /etc/issue
    2  [2013-06-09 10:40:12]   clear
    3  [2013-06-09 10:40:12]   find /etc -name *.conf

%F Equivalent to %Y - %m - %d
%T Equivalent to time ( %H : %M : %S )

We can omit some comands to be displayed on the history file, such as the ones starting with a space, duplicates, or both:

$ export HISTCONTROL= < ignorespace | ignoredups | ignoreboth >

And to ignore certain command - in this case, command history:

$ export HISTIGNORE="history"

To repeat previous commands, we can press CTRL + R and start to write the command, the match in the history record will come up.

To get a full list of the current history we can use the history utility:

$ history[..] 1787  ssh sec02
 1788  ssh sec03
 1789  history
$

To delete the history:

$ history -c$ history
  791  history
$


to delete just one line, for example 791:

history -d 791

The bang bang (!!) is an existing feature to allow executing the latest commands easily. For example:

$ echo uno$ echo dos$ echo tres
$ history 1799  clear
 1800  echo uno
 1801  echo dos
 1802  echo tres
 1803  history
$

to execute the last command (history):

$ !!1799  clear
 1800  echo uno
 1801  echo dos
 1802  echo tres
 1803  history
$

To execute the second command in the list, starting from the last one:

$ !-2echo trestres$


We have something similar with the arguments, using !$. For example, we ping a host and then we telnet the argument using !$:

$ ping localhostPING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.036 ms
[...]
$ telnet !$ 22telnet localhost 22
Trying ::1...
Connected to localhost.
Escape character is '^]'.
SSH-2.0-OpenSSH_6.0p1 Debian-4

There are other combinations with bang, for more information have a look to the linux documentation project.

No comments:

Post a Comment