Categories
SysOps

How to store last command from history

I often want to save a recently executed command to the personal log file for further reference, so let’s do it.

I was told that it would be a hard problem to solve, but it wasn’t. The solution is a simple and well-documented shell function, as an alias would be too simple, shell script too complicated.

You cannot access Bash user history from a shell script in a different way than through the history file
as history commands are disabled within a script. Enabling these would be no use in this case as nobody wants to see only internally executed commands.

Shell function definition

#!/bin/bash 
# Define slc function to store last command with additional commentary inside defined log file
# 
# Use the following construnct inside /.bashrc file to use defined function in the current shell context.
#   source /path/to/slc.sh
#
# Usage
# $ any command
# $ slc
#
# $ any command
# $ slc some comment

# log file
slc_log_file="${HOME}/commands.log"

function slc() {
  # get the last command, but ignore this function
  if [ -z "$(echo $HISTIGNORE | grep slc\\*)" ]; then     # skip last command (function execution)
    command=$(history | tail -2 | grep -v \ slc | tail -1 | sed 's/^[ 0-9:\\-]*//')
  else                                                    # HISTIGNORE does contain slc*
    command=$(history | tail -1 | sed 's/^[ 0-9:\\-]*//')
  fi

  # store date, comment, command
  if [ -n "$command" ]; then
    date=$(date +"%d-%m-%Y %H:%M")
    echo -e "* $date\t$*\n\t$command\n" >> ${slc_log_file}
  fi
}
Include the above shell script inside ~/.bashrc file to use defined slc function.
$ tail -1 ~/.bashrc
source /home/milosz/bin/slc.sh

Examples

Store command and additional commentary.

$ apt-cache search ^cmus
$ slc cmus - an interesting console music player
$ EDITOR=vim mc
$ slc execute mc, use vim editor

Store command without additional commentary.

$ ls
$ slc

The resulting log file is presented below.

$ cat ~/commands.log
* 08-12-2014 22:20	cmus - an interesting console music player
	apt-cache search ^cmus
* 08-12-2014 22:33	execute mc, use vim editor
	EDITOR=vim mc
* 08-12-2014 22:34
	ls

Ending notes

The slc function is written in such a way that it doesn’t matter if you ignore it in history or not (HISTIGNORE variable), or use additional timestamps (HISTTIMEFORMAT variable).