Search This Blog

Sunday, February 9, 2020

Linux Command History

How to command history is saved in Linux
Command history is saved in .bash_history file by history command.

Customization :
1 - Location
You can change history file location of by overwriting HISTFILE

2 - Time
By default, history doesn't store the time of command execution you can provide HISTTIMEFORMAT to store it

    # for storing the date in history in %Y-%M-%D %HH:%MM:%SS
    export HISTTIMEFORMAT="%F %T: "

3 - History limit
The default size of history is 500 you can increase by overwriting the following variables

    # .bash_history file events limit
    export HISTFILESIZE=20000

    # history command events limit
    export HISTSIZE=10000

Productivity Hack: Use CTRL + R to cycle through history to reuse previously executed command rather than finding by clicking up arrow repeatedly.

Problem: If you are using multiple ssh or tmux sessions, and CTRL + R won't display other sessions command because history is not dumped in the file unless a session is closed gracefully.
There is also the chance of losing history on abruptly closing sessions.
Hack: http://northernmost.org/blog/flush-bash_history-after-each-command/

    export PROMPT_COMMAND='history -a'

Explanation:
history -a appends the current history buffer in .bash_history file
The value of the variable  PROMPT_COMMAND  is examined just before Bash prints each primary prompt (PS1).
PS1  is the primary prompt which is displayed before each command

    [ash-ishh@xBot ~]$ echo $PS1
    [\u@\h \W]\$

If  PROMPT_COMMAND is set and has a non-null value, then the value is executed just as if it had been typed on the command line.

List of possible escape sequences: https://www.gnu.org/software/bash/manual/html_node/Controlling-the-Prompt.html