rpayanm
rpayanm

Reputation: 6553

How recover local branch deleted

I created a local branch and push to server:

$ git checkout -b feature
....    
$ git pull origin feature

If I deleted this branch:

$ git branch -D feature

How I recover again this branch from remote server. I try with:

$ git pull
Current branch master is up to date.
$ git branch
* master

Upvotes: 2

Views: 1496

Answers (3)

GianArb
GianArb

Reputation: 1694

git checkout -b feature origin/feature

origin is your remote :)

Upvotes: 1

Hesham Saleh
Hesham Saleh

Reputation: 449

As GianArb said, you can simply checkout the remote branch again, however, if you have made local commits that you didn't push, you don't get them back.

Instead, you can try to locate their hashes back using git reflog, then git checkout $1 where $1 is the potential most recent local commit hash you could find, you will be in a detached HEAD state so you need to branch to a new branch afterwards using git checkout -b new_branch_name.

Upvotes: 3

Makoto
Makoto

Reputation: 106508

If you forcefully deleted the branch (or were required to), you likely lost some commits. (Conversely, git branch -d <branch> going through successfully implies that the branch you have is fully merged in.)

If you haven't cleared your terminal yet, you'll see a message like this:

Deleted branch feature (was <SHA>).

Restoring what was originally coming from your remote is simple...

git checkout feature

The above will automatically create the remote tracking branch.

However, if you need to restore your old branch because there were unmerged changes, you'd need to do a little more.

git checkout <SHA>
git checkout -b feature
git branch -u origin/feature

The above will:

  • Put you in a detached HEAD state
  • Create a branch called feature
  • Set the branch you're on (at this point, feature) to have an upstream of origin/feature

Upvotes: 4

Related Questions