I want to stop myself accidently commiting something to the master branch unless I am sure. So I tried this script to determine which branch I am on but there is a problem. When I create a new branch git name-rev returns master even though I am on the other branch
$ git branch
ignore
master
* set_support
$ git name-rev --name-only HEAD
master
This is my script.
#!/bin/sh
# Check to see if we are on master branch. Stop accidental commits
if [ "`git name-rev --name-only HEAD`" == "master" ]
then
if [ -f i_want_to_commit_to_master ]
then
rm i_want_to_commit_to_master
exit 0
else
echo "Cannot commit to master branch Adrian"
echo "Remember to create file 'touch i_want_to_commit_to_master' to commit to master"
fi
exit 1
fi
exit 0
For Mark: I rebuilt git against latest stable tag and same results. It only works after a commit is made to the new branch.
$ mkdir gittest
$ cd gittest
$ git init
Initialized empty Git repository in /home/adrian/gittest/.git/
$ touch file1
$ git add file1
$ git commit
[master (root-commit) 7c56424] New file
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 file1
$ git branch
* master
$ git checkout -b new_branch
Switched to a new branch 'new_branch'
$ git name-rev --name-only HEAD
master
$ git --version
git version 1.7.7.1
$ git branch
master
* new_branch
$ touch file2
$ git add file2
$ git commit
[new_branch 1e038fb] new file
0 files changed, 0 insertions(+), 0 deletions(-)
create mode 100644 file2
$ git name-rev --name-only HEAD
new_branch
This command is used to find a friendly name of a commit. What is happening is that HEAD is resolving to the sha1 of the commit first and then a name is determined. I’m guessing it is arbitrarily picking master for the name as it comes up first in what
git log --decoratewould come across.I would just parse the output of
git branchin your test:or a more direct way would be: