Command history in Linux

When you type commands in shell, all those commands are saved in history file in Linux. So next time, you can execute the commands in history using shortcuts. This saves your time.

You can set the history size using below syntax. Below command will instruct shell to save only 111 latest commands in the history.

$ set history=111

To display all commands in the history, you can use below syntax.

$ history

Here are some of the shortcuts to execute the commands in the history.

  1. $ !! – This is used to execute last command.
  2. $ !-n – This is used to execute second last command.
  3. $ !n – This is used to execute nth command in the list.

You should also remember below things when working with BASH.

  1. !! – Execute last command
  2.  !xyz – Execute the command (starting with xyz) from the command history
  3.  !xyz:p – Print the command (starting with xyz) from the command history
  4.  !$ – Execute the last argument of previous command. Note that argument should be the command. For example let us say you execute below command.ls -a
    And then execute !$ command. Then bash will execute command “-a”. But since it is not a valid command, you will get an error message saying  -a : command not found.
  5.  !* – Execute the all arguments of previous command. Note that all arguments combined together should be a the commandFor example let us say you execute below command.
    ls -a -l
    And then execute !$ command. Then bash will execute command “-a -l”. But since it is not a valid command, you will get an error message saying
    -a : command not found.
  6.  ^xyz^pqr – Run previous command replacing xyz with pqr. Note that only command string is replaced ..not the arguments

You can also erase and ignore duplicate commands by configuring below variables.

  1. export HISTCONTROL=erasedups
  2. export HISTCONTROL=ignoredups

To ignore the commands starting with space, you can use below command.
export HISTCONTROL=ignorespace

To clear history, you can use below command.

$ history -c

To disable history, you can use below command.

$ export HISTSIZE=0

You may also like...