6
3

More than 1 year has passed since last update.

gitでブランチのバックアップを取る方法

Posted at

はじめに

gitでrebaseなどのためにforce pushを行うと、remoteの状態も上書きされるのでなにかの問題が発生した時に簡単に戻せなくなります。

それを避けるため、事前にバックアップを取るのが安全です。GitのGUIでブランチをコピーするなどの機能がありますが、コマンドラインを使っていればどうすればいいでしょうか?ここでgitのコマンドラインでバックアップを取る方法を紹介します。

バックアップの手順

まずはバックアップしたいブランチをcheckoutし、git branch -mで名前を変更します。

% git checkout my-branch
% git branch -m my-branch_backup

checkoutしているブランチ以外のブランチも名前を変更できます。

% git branch -m [currentBranchName] [newBranchName]

改めてremoteのmy-branchをcheckoutすれば、安心してrebaseなどの作業ができます。

% git checkout my-branch
% git rebase master
% git push-f my-branch

著者は git branch -mを習慣的に使っていますが、git branch -cで名前変更ではなくコピーを作ることもできます。-cを使うと最後にremoteからもう一度checkoutする必要はないので少し楽かもしれません。

% git checkout my-branch
Switched to branch 'my-branch'
% git branch -m my-branch_backup
% git branch
  master
* my-branch_backup
% git checkout my-branch
Switched to branch 'my-branch'
% git branch -c my-branch_backup
% git branch
  master
* my-branch
  my-branch_backup

バックアップを復活する方法

バックアップを取ったあとの作業でremoteのブランチに問題が発生したら、ローカルで取ったバックアップで状態を戻すことができます。

名前変更でもコピーでも、バックアップのブランチは元々のブランチのupstreamもコピーしているので、pushすると以下のメッセージが出ます。

% git push
fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:my-branch

To push to the branch of the same name on the remote, use

    git push origin HEAD

To choose either option permanently, see push.default in 'git help config'.

元々のブランチをバックアップの状態に戻したいので、おそらく一つ目の「push to the upstream branch
on the remote」がしたいでしょう。

% git push origin HEAD:my-branch

また、元々のブランチが使えない状態になってしまっている可能性が高いので、バックアップの手順を逆にしてバックアップブランチの名前を元に戻すこともできます。

% git checkout my-branch_backup
% git branch -M my-branch
% git push -f

git branchで大文字のMのオプションを使うと、存在するブランチを上書きできます。
上のコマンドを実行するとremoteに存在するブランチもそのブランチの状態がバックアップを取る前の状態に戻ります。

% git branch
  main
* my-branch

まとめ

以上、gitブランチのバックアップと復活の方法でした。git branchのコマンドについてもっと知りたい方はdocsを見てください。

6
3
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
6
3