Is there a Git command (or a short sequence of commands) that will safely and surely do the following?
Currently I'm stuck with:
git fetch -p
git stash
git stash drop
git checkout $branch
git pull
but it's bothering me because I'm asked for password two times (by fetch
and pull
). Generally I would be happy with any solution as long as the password is needed only once.
A couple of notes:
Checkout old commitsSince this has the potential to overwrite local changes, Git forces you to commit or stash any changes in the working directory that will be lost during the checkout operation. Unlike git reset , git checkout doesn't move any branches around.
There are two Git commands a developer must use in order to discard all local changes in Git, remove all uncommited changes and revert their Git working tree back to the state it was in when the last commit took place. The commands to discard all local changes in Git are: git reset –hard. git clean -fxd.
You could follow a solution similar to "How do I force “git pull” to overwrite local files?":
git fetch --all
git reset --hard origin/abranch
git checkout abranch
That would involve only one fetch.
With Git 2.23+, git checkout
is replaced here with git switch
(presented here) (still experimental).
git switch -f $branch
(with -f
being an alias for --discard-changes
, as noted in Jan's answer)
Proceed even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If you do not want to switch branch, but only restore a folder from another branch, then git restore
is the other command which replaces the old obsolete and confusing git checkout
.
I presented git restore
here.
git restore --source=anotherBranch --staged] [--worktree -- aFolder
# or, shorter:
git restore -s anotherBranch -SW -- aFolder
Couple of points:
git stash
+ git stash drop
could be replaced with git reset --hard
... or, even shorter, add -f
to checkout
command:
git checkout -f -b $branch
That will discard any local changes, just as if git reset --hard
was used prior to checkout.
As for the main question:
instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch
, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With