Search code examples
bashpromptbuilt-in

Get last executed command in bash


I need to know what was the last command executed while setting my bash prompt in the function corresponding to PROMPT_COMMAND. I have code as follows

function bash_prompt_command () { 
...
    local last_cmd="$(history | tail -n 2 | head -n 1  | tr -s ' ' | cut -d ' ' -f3-)"
    [[ ${last_cmd} =~ .*git\s+checkout.* ]] && ( ... )
...
}

Is there is faster(bash built-in way) to know the what was the command which invoked PROMPT_COMMAND. I tried using BASH_COMMAND, but that too does not return the command which actually invoked PROMPT_COMMAND.


Solution

  • General case: Collecting all commands

    You can use a DEBUG trap to store each command before it's run.

    store_command() {
      declare -g last_command current_command
      last_command=$current_command
      current_command=$BASH_COMMAND
      return 0
    }
    trap store_command DEBUG
    

    ...and thereafter you can check "$last_command"


    Special case: Only trying to shadow one (sub)command

    If you only want to change how one command operates, you can just shadow that one command. For git checkout:

    git() {
      # if $1 is not checkout, just run real git and pretend we weren't here
      [[ $1 = checkout ]] || { command git "$@"; return; }
      # if $1 _is_ checkout, run real git and do our own thing
      local rc=0
      command git "$@" || rc=$?
      ran_checkout=1 # ...put the extra code you want to run here...
      return "$rc"
    }
    

    ...potentially used from something like:

    bash_prompt_command() {
      if (( ran_checkout )); then
        ran_checkout=0
        : "do special thing here"
      else
        : "do other thing here"
      fi
    }