4

How to detect if a branch exists using git command?

Need this in some shell script

DeepNightTwo
  • 4,809
  • 8
  • 46
  • 60
  • Try running the following ,will show you all branches in terms of file. `ls .git/refs/heads/ `.You can combine find with it to check if a file exists find .git/refs/heads/ -type f – h0lyalg0rithm Aug 10 '15 at 08:12
  • Note: you can get a list of local branches with `git branch --list` – Paul Aug 10 '15 at 08:16

1 Answers1

14

To check whether the string in the shell variable $REVISION correctly resolves to a valid object in git's database, you can use

git rev-parse --quiet --verify $REVISION

This will print the SHA1 to stdout if the revision is found, and return with a non-zero exit status otherwise, so you can use it in if clauses:

if git rev-parse --quiet --verify $REVISION > /dev/null; then
    # whatever
fi

Note that this will not only allow branch names in the strict sense, but all valid revision references.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • Thanks for this. I was looking for something quick like this for use in a release process and found that the above solution doesn't work quite the way I'd hoped. In quiet mode, the return value is 1 whether the branch existed or not. Without --quiet the return was 128 with a 'fatal' msg when the branch didn't exist, and it returned 1 and a SHA1. I may use it w/o --quiet and throw the output away. – Sue Mynott Feb 01 '22 at 10:51
  • 1
    @SueSpence This is strange. The command exits with a zero exit code for me if the given revision is valid, and only errors out if the revision is invalid. I tested his when I wrote this answer, and I just tested it again. It's also what the documentation says. It's hard to tell why it doesn't work for you. – Sven Marnach Feb 01 '22 at 12:57
  • I tried this manually on macos on the command line, checking $? afterwards. I reproduced it (or so I thought) several times. Today, so far not seeing that behaviour. I'll edit my original comment later on. – Sue Mynott Feb 02 '22 at 13:06