How to store last command from history

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

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

You cannot access Bash user history from shell script in other way then 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

# 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/
# Usage
# $ any command
# $ slc
# $ any command
# $ slc some comment

# log file

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:\\-]*//')

  # 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}
Include the above shell script inside ~/.bashrc file to use defined slc function.
$ tail -1 ~/.bashrc 
source /home/milosz/bin/


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	

Ending notes

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