DenCowboy DenCowboy - 6 months ago 37
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:


I want to cut the
part so I can use

This is what I tried:


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

The output is

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


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

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


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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download