DenCowboy DenCowboy - 28 days ago 9
Git Question

Cut first part of a string which contains a '/' in bash

In a bash script I want to cut a branch name.
The branch name is always like:

origin/X.X.X-name

I want to cut the
origin/
part so I can use
X.X.X-name
.

This is what I tried:

TEST=origin/1.1.1-name

echo "${TEST//origin/}";


The output is
/1.1.1-name

How can I get rid of the
/
in the beginning using the same approach as I'm doing now. I do not prefer to start cutting etc.

Answer Source

Just use parameter expansion in bash

test=origin/1.1.1-name

printf "%s\n" "${test##*/}"
1.1.1-name

From this Parameter-expansion documentation under sub-string removal.

${PARAMETER##PATTERN}

This form is to remove the described pattern trying to match it from the beginning of the string. The operator # will try to remove the shortest text matching the pattern, while ## tries to do it with the longest text matching.

You also could use the regex operator bash provides (relatively newer versions of bash) to match the string.

[[ $test =~ /(.*)$ ]] && printf "%s\n" "${BASH_REMATCH[1]}"

You could of course third-party shell utils for this also, e.g using cut

cut -d/ -f2 <<<"$test"

meaning using de-limiter / cut the second field (-f2).