Check If Last Command Was Empty in PROMPT_COMMAND

bashprompt

In bash, from inside PROMPT_COMMAND, is there a way to tell if the user just hit 'return' and didn't enter a command?

Best Answer

Check whether the history number was incremented. A cancelled prompt or a prompt where the user just pressed Enter won't increment the history number.

The history number is available in the variable HISTCMD, but this is not available in PROMPT_COMMAND (because what you want there is in fact the history number of the previous command; the command that executes PROMPT_COMMAND itself has no history number). You can get the number from the output of fc.

prompt_command () {
  HISTCMD_previous=$(fc -l -1); HISTCMD_previous=${HISTCMD_previous%%$'[\t ]'*}
  if [[ -z $HISTCMD_before_last ]]; then
    # initial prompt
  elif [[ $HISTCMD_before_last = "$HISTCMD_previous" ]]; then
    # cancelled prompt
  else
    # a command was run
  fi
  HISTCMD_before_last=$HISTCMD_previous
}
PROMPT_COMMAND='prompt_command'

Note that if you've turned on squashing of duplicates in the history (HISTCONTROL=ignoredups or HISTCONTROL=erasedups), this will mistakenly report an empty command after running two identical commands successively.

Related Question