gitgit-bashgit-for-windowsgit-alias

Using a local variable in a function when setting a git alias


I am using Windows 11 and git and trying to create a alias which will checkout and pull a branch before checking out the original branch, merging the just pulled branch and then push. I am having trouble setting a local variable for the original branch:

git config --global alias.sync "!f() { \
        CURRENT_BRANCH=($`git rev-parse --abbrev-ref HEAD`) && echo $CURRENT_BRANCH && \
        git checkout main && git pull && \
        git checkout $CURRENT_BRANCH && git merge main && \
        git push; \
      }; f"

In the above the echo $CURRENT_BRANCH statement (there for testing) always prints blank. What's going wrong? I've tried the following in case it's the syntax which is wrong but again just a blank line is printed.

git config --global alias.sync "!f() { \
        CURRENT_BRANCH=TEST && echo $CURRENT_BRANCH; \
      }; f"

Solution

  • There's a problem with your aliases: bash expands "!" and "$CURRENT_BRANCH" in double quotes when you declare the alias, not when you call it. To protect the code either use apostrophes (single quotes ') instead of double quotes:

    git config --global alias.sync '!f() { \
            CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) && echo $CURRENT_BRANCH && \
            git checkout main && git pull && \
            git checkout $CURRENT_BRANCH && git merge main && \
            git push; \
          }; f'
    

    or escape shell metacharcters with backslashes:

    git config --global alias.sync "\!f() { \
            CURRENT_BRANCH=\$(git rev-parse --abbrev-ref HEAD) && echo \$CURRENT_BRANCH && \
            git checkout main && git pull && \
            git checkout \$CURRENT_BRANCH && git merge main && \
            git push; \
          }; f"
    

    PS. I also fixed $() syntax.