git pullはエイリアスで現在のブランチをプルするとミスが減る

git pullはエイリアスが早くて安全

Gitを使用していると git pull コマンドがよく使われますが、現在のブランチが feature/foo なのに間違えて feature/bar や main など現在以外のブランチを git pull コマンドで誤って読み込んでしまう人は多いです。

しかも手作業だと git pull origin feature/foo-bar-baz-hoge-fuga のように長いブランチ名だと入力するのに時間がかかり、間違える可能性も高くなります。

この問題は現在のブランチをプルするエイリアスを登録することで解決できます。

私の場合は「pcb」を実行するだけで「git pull origin 現在のブランチ」が実行されるようにしています。

この動画はmainブランチなので「git pull origin main」が実行されていますが、例えば現在のブランチが feature/foo の場合は「git pull origin feature/foo」が実行されます。

git pullはエイリアスで現在のブランチをプルするとミスが減る

※ 登録するエイリアス名は任意です。pcbはpull current branchの略。

git pullのエイリアスの登録方法

git pullのエイリアスの登録方法はMacとWindowsで異なります。

Macのエイリアスの登録方法

ターミナルで「open ~/.bashrc」を実行して.bashrcを開きます。

open ~/.bashrc

.bashrcに以下のコードを貼り付けて保存します。

# git pull origin [現在のブランチ] を実行する
pcb () {
    currentBranch=$(git rev-parse --abbrev-ref HEAD)
    echo "git pull origin $currentBranch を実行します。"
    git pull origin "$currentBranch"
}

最後に「source ~/.bashrc」を実行して読み込めば、pcbコマンドで実行できます。

Windowsのエイリアスの登録方法

Profile.ps1ファイルを作成して以下のコードを保存します。

Profile.ps1
# 現在のブランチでgit pullを実行
function pullCurrentBranch {
  $currentBranch = git rev-parse --abbrev-ref HEAD
  Write-Output "git pull origin $currentBranch を実行します。"
  git pull origin $currentBranch
}
Set-Alias -Name pcb -Value pullCurrentBranch

作成したProfile.ps1ファイルを以下の場所に保存します。

C:\Users\ユーザー名\Documents\PowerShell\Profile.ps1

これでWindowsのPowerShellでも「pcb」を実行するだけで「git pull origin 現在のブランチ」が実行されるようになります。