0
0

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を使ってgit shashとかcheckoutとかをコンソール上で選択できるようにする

0
Last updated at Posted at 2021-02-27

TO;DR

  1. list出力
  2. pecoで選択
  3. テキトーに編集
  4. 必要なコマンドに渡す

これでラクしちゃおうぜ

環境

  • macOS Mojave 10.14.16
  • bash

本題

経緯

$ git stash push -m "xxx"

でファイルの一時退避したりすることが増えてきたので、もうちょいラクにapplyとかdropとかできないかな〜と思ってしまったため
(他にもDockerのコンテナ名拾いたい時とかに応用できそう)

  • コマンド
$ git stash list | peco | awk -F ':' '{print $1}'  | xargs -IXXX git stash apply XXX'
  • エイリアス(.bashrc)
.bashrc
# bashの「'」はエスケープが必要なので「'\'」を入れてる
alias gsa='git stash list | peco | awk -F '\'':'\'' '\''{print $1}'\''  | xargs -IXXX git stash apply XXX'

解説

git stash list
  • まずはリスト出力しパイプでpecoに渡します
peco
  • 「標準入力から行データを受け、その中から行を選択し、それを標準出力に返す」コマンド

  • Homebrewが使えるなら brew install pecoで一発!

    • それ以外のパターンなら調べてね...
  • ここまでで「stashのリストから選択して1行の標準出力を得る」まで出来ます

awk -F ':' '{print $1}'
  • awk

    • 受けた1行データをサクッと編集してくれるコマンド

    • 「-F」オプション

      • 区切り文字を指定
      • 今回は"git stash list"の出力が以下の通りで、「:」の直前までがほしいので指定している
        • 例  stash@{0}: On (ブランチ名): テスト
        • この「stash@{x}」がほしい!
    • {print $1}

      • 区切られた文字列の中から1番目を標準出力に返す
  • ここまでで「stashのリストから選択した行の"stash@{x}"の標準出力を得る」まで出来ます

xargs -IXXX git stash apply XXX'
  • xargs

    • コマンドを組み立てます

    • 「-I」オプション

      • 続く文字列(ここではXXX)をコマンドの中で置換します
      • ここにパイプで繋いできた"stash@{x}"の標準出力が入る!
    • git stash apply XXX

      • "XXX"が"stash@{x}"に置換される
  • これで「stashのリストから選択した行をapply」ができます!

おまけ

.bashrc
#gitにpecoを組み込む
## チェックアウト
alias gc='git branch | peco | xargs git checkout'
## ブランチ削除
alias gbd='git branch | peco | xargs git branch -d'

このへんはpecoで選択した行を編集する必要がないのでawk不要でラクですね!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?