0

I am writing a bash shell script (a git extension which adds a new command to git), and I would like to find out the "source branch" of the currently-active merge, so I can abort the merge and subsequently restart it. How can I obtain this information?

Robin Green
  • 32,079
  • 16
  • 104
  • 187

1 Answers1

0

To do this, in a way that works with git worktrees created by the git worktree command, it's first necessary to find out the current GIT_DIR. Fortunately, git provides a command to set this variable, which you can call from your scripts:

. "$(git --exec-path)/git-sh-setup"

Then you can just cat the required file:

merge_source=$(cat "$GIT_DIR/MERGE_HEAD")

This contains the long git hash of the merge source of the current merge, i.e. the commit which is currently being merged into HEAD.

If the file doesn't exist, it means there is no merge currently being done.

Robin Green
  • 32,079
  • 16
  • 104
  • 187
  • 1
    Shorter: `git rev-parse --git-dir` gives you the appropriate information. For that matter, instead of `cat $(git rev-parse --git-dir)/MERGE_HEAD`, you can just use `git rev-parse MERGE_HEAD` here. ... Ah, I see you added this to the linked duplicate. My answer there shows the long way because the OP should also inspect the MERGE_MSG file, which rev-parse doesn't do. Also worth noting: `git-sh-setup` will be on `$PATH` when the command is run via the `git` front end, so if you name your script `git-foo-bar` and run `git foo-bar` and have your script in your path, just use `. git-sh-setup`. – torek Nov 09 '19 at 18:57