LoginSignup
5
4

More than 5 years have passed since last update.

シェルコマンド履歴を簡単にコピーするシェル関数

Last updated at Posted at 2015-03-23
  • historyコマンドの出力をどうにかする。

n個前のコマンドをコピー

  • historyコマンドの出力にはそれ自身が含まれるため、直前のコマンドを表示するにはhistory 2とする必要がある
    • それは直感に反するので引数に+1する
  • historyコマンドの出力は、以下のようにスペース2個で区切られる
    • cutコマンドでコマンド部分だけを抽出したいが、cutではデリミタに複数の文字を指定できない
    • デリミタをスペース1個にすると、コマンド文はフィールド5以降に当たる
    • awkでスペース2個区切りのフィールド3以降を表示できるが、クッソ長いのでやめた
$ history 1
  508  history 1
# (空白のフィールド1) (空白のフィールド2) 508 (空白のフィールド4) history 1
chis () { #copy shell history
  num=1
  grep -q '^[0-9]$' <<< "$1" && num="$1" # 引数から数値のみを抽出
  history "$((num+1))" | head -n 1 | cut -d ' ' -f 5- | pbcopy
  pbpaste 
}

履歴をpecoで絞り込んでコピー

  • 数字の引数があるか判定
    • あればn個前の履歴から絞り込み
    • なければ全履歴から絞り込み
  • sort -rで逆順にして新しい履歴を上に
    • 最新の履歴はこれ自体なのでsedで削除
shis () { #search shell history
  if grep -q '^[0-9]\+$' <<< "$1";then
    history $(($1 + 1))
  else
    history
  fi | sort -r | sed 1d | peco --prompt "Select history to copy:" | cut -d ' ' -f 5- | pbcopy
  pbpaste
}

履歴をpecoで絞り込んで実行

rhis () { #run shell history
  eval "$(shis "$1")"
}

参考

5
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4