Bash: Double Up / Twice Up for history - Help make this better

This is a bit janky (I originally posted on Allow to open history on double arrow up · Issue #2573 · atuinsh/atuin · GitHub), it does work… What it does is put in the last command when pushing up once, and open history when pushing up twice.

Wonder if others have tips on how to make it less jank…

I also don’t seem to be able to do ctrl-# hot keys for history entries since setting this up.

# MARK: Atuin Customization
eval "$(atuin init bash --disable-up-arrow)"

PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND;}atuin_postexec"
atuin_postexec() {
  if [ -z "${ATUIN_HISTORY_ID}" ]; then
    local LAST_RUN="$(HISTTIMEFORMAT= history 1 | sed 's/^ *[0-9]\+ *//')"
    atuin history start -- "$LAST_RUN" > /dev/null
  fi
  __atuin_up_count=0
}

bind -x '"\e[A": atuin_custom_up_arrow' 2>/dev/null

# Custom up arrow function
atuin_custom_up_arrow() {
    if [ -z "${READLINE_LINE}" ] || (( ${__atuin_up_count:-0} == 0 )); then
        # First press: native Bash history
        __atuin_up_count=1
        READLINE_LINE="$(HISTTIMEFORMAT= history 1 | sed 's/^ *[0-9]\+ *//')"
        READLINE_POINT=${#READLINE_LINE}
        return 0
    else
        # Clear the line for second press so atuin doesn't filter
        local original_line="$READLINE_LINE"
        READLINE_LINE=""
        READLINE_POINT=0

        # Second press: trigger Atuin
        unset ATUIN_HISTORY_ID
        __atuin_history

        # Restore first command if Atuin search aborts 
        if [ -z "${ATUIN_HISTORY_ID}" ]; then
            READLINE_LINE="$original_line"
            READLINE_POINT=${#READLINE_LINE}
        fi
    fi
}

bind -x '"\e[B": atuin_custom_down_arrow' 2>/dev/null
atuin_custom_down_arrow() {
    local last_cmd="$(HISTTIMEFORMAT= history 1 | sed 's/^ *[0-9]\+ *//')"

    if [[ -z "$READLINE_LINE" || "$READLINE_LINE" == "$last_cmd" ]]; then
        # If current line matches last command, clear it
        READLINE_LINE=""
        READLINE_POINT=0
    else
        # Fallback to default "next-history" behavior
        builtin bind '"\e[B": next-history'
        # Simulate down arrow press to trigger the fallback
        READLINE_LINE=$(builtin history -n && history 1 | sed 's/^ *[0-9]\+ *//')
        READLINE_POINT=${#READLINE_LINE}
        # Re-bind custom handler for next time
        bind -x '"\e[B": atuin_custom_down_arrow'
    fi
}
1 Like