Thursday, October 22, 2026

[kllfzlhr] git push to a non-bare repository

git push

"""
remote: error: refusing to update checked out branch: refs/heads/master

By default, updating the current branch in a non-bare repository is denied, because it will make the index and work tree inconsistent with what you pushed, and will require 'git reset --hard' to match the work tree to HEAD.

! [remote rejected] master -> master (branch is currently checked out)

error: failed to push some refs to '/...'
"""

3 ways to avoid this error:

usual method 1: push only to bare repositories.

usual method 2: in the upstream non-bare repository, temporarily switch to a different branch.

this could be done by creating a new branch:

git switch -c temporary

then, later:

git switch -
git branch -d temporary

streamlined method 3: instead of creating a temporary branch upstream at the current commit as above, switch to a detached state at the current commit.  full example:

# upstreamdir is a normal (not bare) git repository
git clone upstreamdir downstreamdir

pushd downstreamdir

# make some edits to an existing file and commit
echo "more stuff" >> "$FILE"
git commit -a -m downstreamdir-commit

popd

pushd upstreamdir

git switch --detach

# succeeds printing empty string
git branch --show-current

popd

pushd downstreamdir

# if not for detach earlier, this would fail with the above error message
git push

popd

pushd upstreamdir

# dash "-" is shortcut to switch to the previous branch without having to type its name
git switch -

# verify no longer detached
git branch --show-current
# prints "master"

# latest commit in upstream
git log -1
# shows "downstreamdir-commit"

popd

No comments :