git: Switch branch and ignore any changes without committing

后端 未结 15 2130
别跟我提以往
别跟我提以往 2020-11-28 00:37

I was working on a git branch and was ready to commit my changes, so I made a commit with a useful commit message. I then absentmindedly made minor changes to the code that

相关标签:
15条回答
  • 2020-11-28 00:47

    Follow these steps:

    1. Git stash save will save all your changes even if you switch between branches.
    git stash save
    
    1. Git checkout any other branch, now since you saved your changes you can move around any branch. The above command will make sure that your changes are saved.
    git checkout branch
    
    1. Now when you come back to the branch use this command to get all your changes back.
    git stash pop
    
    0 讨论(0)
  • 2020-11-28 00:48

    well, it should be

    git stash save
    git checkout branch
    // do something
    git checkout oldbranch
    git stash pop
    
    0 讨论(0)
  • 2020-11-28 00:53

    You need a clean state to change branches. The branch checkout will only be allowed if it does not affect the 'dirty files' (as Charles Bailey remarks in the comments).

    Otherwise, you should either:

    • stash your current change or
    • reset --hard HEAD (if you do not mind losing those minor changes) or
    • checkout -f (When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes. )

    Or, more recently:

    • With Git 2.23 (August 2019) and the new command git switch:
      git switch -f <branch-name>
      (-f is short for --force, which is an alias for --discard-changes)

    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.

    This differs from git switch -m <branch-name>, which triggers a three-way merge between the current branch, your working tree contents, and the new branch is done: you won't loose your work in progress that way.

    0 讨论(0)
  • 2020-11-28 00:53

    Move uncommited changes to a new branch

    I created a .gitconfig alias for this:

    [alias]
    spcosp = !"git stash push && git checkout \"$@\" && git stash pop --index #"
    

    To change to new-branch-name, use:

    git spcosp new-branch-name
    

    And any non-commited file and index changes will be kept.

    0 讨论(0)
  • 2020-11-28 00:58

    Follow,

    $: git checkout -f
    
    $: git checkout next_branch
    
    0 讨论(0)
  • 2020-11-28 00:58

    If you want to keep the changes and change the branch in a single line command

    git stash && git checkout <branch_name> && git stash pop
    
    0 讨论(0)
提交回复
热议问题