ZSH Plugin to Re-Execute the Last Command After Some Number of Empty Prompts

A gif showing this shell script in action where after sending 2 empty command prompts the last non empty command prompt is run

After running a command in the terminal, I often find myself needing to run the same command again. This is especially true when I am working on a project and need to run the same command multiple times in a row.

Or maybe I am remoting into my laptop from my phone and need to run a command that is too long to type out.

I want an easy way to run the last command again without having to type it out or use the up arrow key to find it.

So as I say in the README.md I have created A ZSH Plugin which will re-execute the last command you entered after so many empty commands. The plugin uses an ENV variable named REEXEC_PROMPT_COUNT to determine how many empty commands to execute before re-executing the last command which was not empty. The default count for empty prompts (controlled by an ENV variable) is set to 3. So starting at 0, hitting enter 4 times should rexecute the last command you typed with the default of 3 (it is counting zero based).

The default count feels like a safe number of required empty lines before running the last command. It is unlikely that I would accidentally run the last command by sending a few empty lines in a row. While being easy and quick enough to do that I can deal with the previous mentioned issues easily.

I have moved the usage and installation instructions to the repo here.

At the point of writing or really updating this blog post the contents of the plugin were as follows:

# Plugin to re-execute the last command after a specified number of empty prompts

# Function to initialize variables
function _reexec_init() {
  export EMPTY_PROMPT_COUNT=0
  export LAST_COMMAND=""

  # Set default value for REEXEC_PROMPT_COUNT if not already set
  : ${REEXEC_PROMPT_COUNT:=3}
}

# Function to be called before each prompt
function _reexec_preexec() {
  export EMPTY_PROMPT_COUNT=0
  if [[ -n $1 ]]; then
    export LAST_COMMAND=$1
  fi
}

# Function to be called after each command
function _reexec_precmd() {
  if [[ $EMPTY_PROMPT_COUNT -eq $REEXEC_PROMPT_COUNT && -n $LAST_COMMAND ]]; then
    echo "Executing: $LAST_COMMAND"
    eval "$LAST_COMMAND"
    export EMPTY_PROMPT_COUNT=0
  elif [[ -z $BUFFER ]]; then
    export EMPTY_PROMPT_COUNT=$((EMPTY_PROMPT_COUNT + 1))
  else
    export EMPTY_PROMPT_COUNT=0
  fi
}

# Set up the hooks
function _reexec_setup_hooks() {
  autoload -Uz add-zsh-hook
  add-zsh-hook preexec _reexec_preexec
  add-zsh-hook precmd _reexec_precmd
}

# Initialize and set up hooks when the plugin is loaded
_reexec_init
_reexec_setup_hooks

Follow the instructions here and you easily or lazily be rerunning whatever your working on in no time.