最近、bash の自作コマンド作成にハマっています。 今回は、我ながら便利だなあと思っている作品たちを紹介したいと思います。

必要なもの

自作コマンド(関数)を実装する際に、既存のコマンドを組み合わせるのが手っ取り早いです。

Shell

  • Linux におけるデファクトスタンダードになっている bash を採用
  • 以前は fish を使っていたが、Mac の引っ越しを機に bash に乗り換えることにした

fzf

  • あいまい検索を可能にするコマンド

rg

  • grep の高速版

自作コマンド

dotfiles で管理しています。

あいまい検索でブランチにチェックアウト

  • git ブランチの候補を表示
  • 選択したブランチにチェックアウト
fzf_git_checkout_branch() {
  local selected_branch=$(git branch | sed -r "s/^[ \*]+//" | fzf --reverse)
  if [[ -n "$selected_branch" ]]; then
    local command="git checkout $selected_branch"
    eval "$command"
  fi
}

fzf_git_checkout_branch

RSpec ファイルに絞ってあいまい検索して RSpec を実行

  • ファイル名が *_spec.rb* のものを検索
  • さらに spec/* 配下のファイルに限定( *_spec.rb* のモデルがある可能性があるため)
  • 上記の候補をあいまい検索
  • 選択されたファイルで RSpec を実行
fzf_select_and_run_rspec() {
  local selected_file=$(find . -follow -name "*_spec.rb" | rg 'spec/' | fzf --reverse)
  if [[ -n "$selected_file" ]]; then
    local command="bundle exec rspec $selected_file"
    echo "$command"
    history -s "be rs $selected_file"
    eval "$command"
  fi
}

変更があったファイルに絞ってあいまい検索して RSpec を実行

  • git で変更が記録されたファイル名で絞る
  • さらに *_spec.rb で終わるファイル名で絞る
  • 以上をあいまい検索
  • 選択されたファイルで RSpec を実行
run_selected_changed_spec(){
  local selected_file=$(git diff --name-only | rg '_spec.rb' | fzf --reverse)
  if [[ -n "$selected_file" ]]; then
    echo "bundle exec $selected_file"
    history -s "be rs $selected_file"
    eval "be rs $selected_file"
  fi
}

使い方

エイリアスやキーバインドを登録しておくと便利です。

エイリアス

  • gcob と入力して実行すると、fzf_git_checkout_branch が実行される
alias gcob='fzf_git_checkout_branch'

キーバインド

  • Ctrl + r を押すとコマンドの履歴をあいまい検索
bind -x '"\C-r":"fzf_history"'

参考にしているもの