メモ:pecoをbashで使う

概要

peco を bash で使うときの設定メモ。

元のスクリプトはこちら。

qiita.com

Ctr-C で中断したときに history -d 0 が実行されてしまってエラーがコンソールに出てしまうのだけ修正。

export HISTSIZE=10000
export HISTCONTROL=ignoredups
export HISTIGNORE="fg:bg:history*:cd:ls:exit:pwd"

peco-history() {
  local NUM=$(history | wc -l)
  local FIRST=$((-1*(NUM-1)))

  if [ $FIRST -eq 0 -a $HISTCMD -ge 2 ] ; then
    # Remove the last entry, "peco-history"
    history -d $((HISTCMD-1))
    echo "No history" >&2
    return
  fi

  local CMD=$(fc -l $FIRST | sort -k 2 -k 1nr | uniq -f 1 | sort -nr | sed -E 's/^[0-9]+[[:blank:]]+//' | peco | head -n 1)

  if [ -n "$CMD" ] ; then
    # Replace the last entry, "peco-history", with $CMD
    history -s $CMD

    if type osascript > /dev/null 2>&1 ; then
      # Send UP keystroke to console
      (osascript -e 'tell application "System Events" to keystroke (ASCII character 30)' &)
    fi

    # Uncomment below to execute it here directly
    # echo $CMD >&2
    # eval $CMD
  elif [ $HISTCMD -ge 2 ]; then
    # Remove the last entry, "peco-history"
    history -d $((HISTCMD-1))
  fi
}
bind -x '"\C-r":peco-history'

/以上