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:
* branch-1.0(the prefix is always an asterisk)branch-2.0 remotes/origin/branch-2.0(here may be a new line instead of a space)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)
This is how it can be done in Bash, without using an external regex parser:
Or using a POSIX-shell grammar only:
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.