gitbranch

Switch on another branch (create if not exists), without checking if already exists?


git checkout -b foo switches on foo branch (even if it doesn't exist, it is created), but if the foo branch already exists it throws an error like this:

fatal: A branch named 'foo' already exists.

What's the command that does the following check?


Solution

  • Update Q3 2019 (Git 2.23): there now actually is a git switch command!

    git switch -c aBranch 
    

    Or, if the branch already exists:

    git switch aBranch
    

    As I explained in 2020, the git switch command is "experimental" in name only, and is here to stay.

    You would need an alias though, which tries first to switch to the existing branch and, if it fails (because the branch might actually not exist), creates it:

    switchoc = "!f() { git switch $1 2>/dev/null || git switch -c $1; }; f"
    

    Note the name of the alias: switchoc (for "switch or create").

    That combination git switch+git switch -c does precisely what the OP is asking for.

    As jar pointed out in the comments:

    Anyone trying this in 2021, note that you cannot shadow existing git commands with aliases.
    Since git switch is a git command, this alias (named "switch") won't work. You must create your unique name for the alias, like "switchit" or something.


    bgusach's alias mentioned below in the comment is safer (based on Jiří Pavelka 's answer):

    switch = "!f() { git checkout $1 2>/dev/null || git checkout -b $1; }; f"
    
    git switch abranch
    

    Original answer (2014) You can try:

    git checkout -B foo
    

    From git checkout man page:

    If -B is given, <new_branch> is created if it doesn’t exist; otherwise, it is reset. This is the transactional equivalent of

    $ git branch -f <branch> [<start point>]
    $ git checkout <branch>
    

    As mentioned below, use it with caution as it does reset the branch, which is not always desirable.
    If you did reset the branch by mistake with this command, you can easily revert to its previous state with:

    git reset HEAD@{1}
    

    Tal Jacob - Sir Jacques proposes in the comments:

    Configure git alias with:

    git config alias.switchoc '!f() { git switch $1 2>/dev/null || git switch -c $1; }; f' 
    

    Then use with:

    git switchoc <branch>