0

How can I extract the branch name from a string using bash? For example, I have the following command:

branch=$(git branch -a --contains $sha)

This may return:

  1. * branch-1.0 (the prefix is always an asterisk)

  2. branch-2.0 remotes/origin/branch-2.0 (here may be a new line instead of a space)

  3. master remotes/origin/master (here may be a new line instead of a space)

And I need only the branch name (and only once) - master, branch-2.0 or branch-1.0. I know it can be done with the sed command, but I can't figure out how.

I use the following regex: (branch-[0-9].[0-9])|(master)

John Doe
  • 3
  • 3
  • _I use the following regex:_ : Write the full **sed** command, instead of just mentioning what you are using. Further, write what output you get from your sed-command for which input. – user1934428 Nov 29 '21 at 12:12
  • Simpy `git branch -a | cut -c2-` discards the first two columns. – tripleee Nov 29 '21 at 13:01
  • 1
    You can do `git branch -a --format='%(refname:short)' --contains=$sha` – Philippe Nov 29 '21 at 19:53

2 Answers2

1

This is how it can be done in Bash, without using an external regex parser:

# Read reference name path in an array splitting entries by /
IFS=/ read -ra refname < <(
  # Obtain full branch reference path that contains this sha
  git branch --format='%(refname)' --contains="$sha"
)

# Branch name is the last array element
branchname="${refname[-1]}"

printf 'The git branch name for sha: %s\nis: %s\n' "$sha" "$branchname"

Or using a POSIX-shell grammar only:

# Read reference path
refname=$(
  # Obtain full branch reference path that contains this sha
  git branch --format='%(refname)' --contains="$sha"
)

# Trim-out all leading path to get only the branch name
branchname="${refname##*/}"

printf 'The git branch name for sha: %s\nis: %s\n' "$sha" "$branchname"

EDIT:

As Philippe mentionned --format='%(refname:short) will directly return the branch name without path, thus saving the need for further processing to extract it from the full reference path.

branchname=$(git branch --format='%(refname:short)' --contains="$sha")
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
1

Using sed

$ branch=$(git branch -a --contains $sha | sed 's#.*/\|[^a-z]*##')

Using awk

$ branch=$(git branch -a --contains $sha | awk -F/ '{gsub("* ","");print $NF}')
HatLess
  • 10,622
  • 5
  • 14
  • 32
  • 1
    Sorry, I can't vote yet) When I have enough reputation, I will vote for your answer. Thank you for your help! – John Doe Nov 29 '21 at 13:02