基本cursor
を用いて開発していますが、gitの操作はGUIではなくterminal
でやるタイプの人間です。
本記事では、ローカルブランチを簡単に切り替えるスクリプトを設定するスクリプトの作成とエイリアスの設定方法を簡単に説明します。
設定するとできること
$ gsw
を実行すると、
Current branch: {current branch}
Select a branch to switch to:
1) {local branch 1}
2) {local branch 2}
3) main
Enter number (1-3): 2
Switching to branch: {local branch 2}
Switched to branch '{local branch 2}'
Successfully switched to {local branch 2}
のように現在のローカルブランチの一覧が表示され、任意のブランチを選択することでswitchできます
設定方法
環境はLinux, macOSを想定しています。
スクリプト作成
ホームディレクトリにgsw.sh
を作成します
$ nano ~/gsw.sh
or
$ vim ~/gsw.sh
など
gsw.sh
に以下をコピペ
#!/bin/bash
# Git Switch with branch selection
# Usage: gsw
# 現在のブランチを取得
current_branch=$(git branch --show-current 2>/dev/null)
# Gitリポジトリ内かチェック
if [ $? -ne 0 ]; then
echo "Error: Not in a git repository"
exit 1
fi
# ローカルブランチ一覧を取得(現在のブランチを除く)
branches=$(git branch | grep -v "^\*" | sed 's/^[ ]*//g')
# ブランチが存在しない場合
if [ -z "$branches" ]; then
echo "No other local branches found."
exit 0
fi
echo "Current branch: $current_branch"
echo ""
echo "Select a branch to switch to:"
# ブランチを配列に格納
branch_array=()
counter=1
while IFS= read -r branch; do
echo " $counter) $branch"
branch_array+=("$branch")
((counter++))
done <<< "$branches"
echo ""
read -p "Enter number (1-$((counter-1))): " selection
# 入力検証
if ! [[ "$selection" =~ ^[0-9]+$ ]] || [ "$selection" -lt 1 ] || [ "$selection" -gt $((counter-1)) ]; then
echo "Invalid selection. Exiting."
exit 1
fi
# 選択されたブランチを取得
selected_branch=${branch_array[$((selection-1))]}
# ブランチを切り替え
echo "Switching to branch: $selected_branch"
git switch "$selected_branch"
if [ $? -eq 0 ]; then
echo "Successfully switched to $selected_branch"
else
echo "Failed to switch to $selected_branch"
exit 1
fi
実行権限を付与
$ chmod +x ~/gsw.sh
エイリアスを設定
bashの場合
$ echo 'alias gsw="~/gsw.sh"' >> ~/.bashrc
$ source ~/.bashrc
zshの場合
$ echo 'alias gsw="~/gsw.sh"' >> ~/.zshrc
$ source ~/.zshrc
使用方法
# Gitリポジトリ内で実行
$ gsw