Bash programming/Bash History

From Wikiversity
Jump to navigation Jump to search

Bash Command history feature allows to recall, edit and rerun previous commands. Also allows commands to be saved using the history -a command[1][2].

Variables to control Bash History:

  • HISTFILE[3]: The default value is ~/.bash_history

Usage[edit | edit source]

  • Basic example:
export PROMPT_COMMAND='history -a'
  • Advanced examples:

Logging[edit | edit source]

If you wish to keep a record of your commands, you can configure bash to write a log file of entered commands.

Logging can be set up automatically by running these commands:

printf "local6.* /var/log/commands.log" |sudo tee /etc/rsyslog.d/bash.conf >>/dev/null
echo "export PROMPT_COMMAND='"RETRN_VAL=\$?\;logger -p local6.debug "\"\$(whoami) \$(tty) [\$\$]: \$(history 1 | sed \"s/^[ ]*[0-9]\\+[ ]*//\" ) [\$RETRN_VAL]"\"\' >>~/.bashrc
systemctl restart rsyslog
  • The first line creates a configuration file for rsyslog contaning the log file destination /var/log/commands.log, which may be changed as desired. The >>/dev/null part prevents redundantly outputting the text into the command line window.
  • The second adds the log line definition export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "$(whoami) $(tty) [$$]: $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"' to ~/.bashrc, which runs upon each start of the terminal.
  • The third line restarts the rsyslog service to make the changes effective.

Activities[edit | edit source]

  1. Install bash customization

See also[edit | edit source]

  3. <