4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pecoを用いたコマンド履歴出す機能を作るときに調査したことまとめ

Last updated at Posted at 2022-03-13

本記事について

pecoを使って少しでも仕事を早くする
pecoを使って端末操作を爆速にする

を見て、どうしてこの書き方なのかっていうのを調べた。

結果

.zshrc
alias tac='tail -r'
alias distinct='awk '\''!a[$0]++'\'

# peco
function peco-select-history() {
    BUFFER=`history -n 1 | tac | distinct | peco`
    CURSOR=${#BUFFER}
    zle reset-prompt
}

zle -N peco-select-history
bindkey '^r' peco-select-history

こうなった。

調査メモ

ショートカットからコマンド呼び出す。

zshの機能
https://qiita.com/yuku_t/items/e58cbecf13407446bd50

zleって何?

Zsh Line Editor
https://dev.classmethod.jp/articles/zsh-zle-introduction/

history コマンド

fc コマンド

つまり

history
=> fc -l
=> 履歴を16件表示するコマンド
履歴には番号がついている

オプション
n: 番号を表示しない
数字: この数字以降の番号の履歴を表示。つまり、1なら全部

tac コマンド

入力を逆順で表示する
https://hydrocul.github.io/wiki/commands/tac.html
これで最新が上に来るようになる。
catを逆にしてるからtacって名前

macにはデフォルトで入ってない。

tail -r

https://hydrocul.github.io/wiki/commands/tail.html
https://xtech.nikkei.com/it/atcl/column/15/042000103/080400023/

macでtacしたい場合

じゃあどうする?

選択肢
whichでtacかtail -rか分岐
macでtacを使えるようにする
tail -r を使う

tail -r よりもtacのほうが直感的なので2番目で

.zshrc
alias tac='tail -r'

awkで重複削除

awkで重複削除
https://qiita.com/pocket8137/items/a6de22d0be6b26f7bcac

uniqだとsortが必要になるのでだめ。
=> わかりづらいので名前変えたい
distinctでよいのでは

変数展開を行わないようにしないといけない
https://qiita.com/y518gaku/items/35870f379bc4b0b85f72#%E3%82%AF%E3%82%A6%E3%82%A9%E3%83%BC%E3%83%86%E3%82%A3%E3%83%B3%E3%82%B0

.zshrc
alias distinct='awk '\''!a[$0]++'\'

zle BUFFERとCURSOL

https://dev.classmethod.jp/articles/zsh-zle-introduction/
これ読めばわかる

${#BUFFER}

文字列の長さ
http://dhythm.blog11.fc2.com/blog-entry-156.html

shellにおけるバッククォート

shell バッククォート
https://uxmilk.jp/27649

reset-promptとかの意味

いろいろ書いてある
https://qiita.com/b4b4r07/items/8db0257d2e6f6b19ecb9

結局なんでやってるのかわからなかったので以下で検証した

何もなし
redisplay
clear-screen
reset-prompt
何もなし => 表示される(これでいいのでは?)
redisplay => 表示される(違いわからない)
clear-screen => 端末のリセットされて表示される。これは嫌
reset-prompt => 表示される(違いわからない)

とりあえずキーバインドの記事でも元記事でもreset-prompt使ってたし、reset-prompt使うことにした。

4
1
0

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?