How shell fetches strings according to rules

topic description

str = "master  7ecbf3f [origin/master: ahead 8, behind 1] local"

1. How to get the string origin/master: ahead 8, behind 1 between []?
2. How to tell that the string fetched in 1 contains behind or diverged ?
Shell is so fascinating, solve!

May.28,2022

-sharp!/bin/sh
str='master 7ecbf3f [origin/master: ahead 8, behind 1] local'
str_sub=`echo $str | grep -Po '(?<=\[).*(?=\])'`
echo " ${str_sub}"
`echo $str_sub | grep -q 'behind'`
ret=$?
if [ $ret -eq 0 ];then
    echo ' behind'
fi

execution result

[root@chengqm ~]-sharp sh test.sh 
 origin/master: ahead 8, behind 1
 behind

as a final reminder, there can be no spaces on both sides of the = sign in shell


1. How to get the strings origin/master: ahead 8, behind 1 between []?

str='master 7ecbf3f [origin/master: ahead 8, behind 1] local'
-sharp
grep -Po '\[\K[^]]+' <<<$str
-sharp
sed 's/[^[]\+\[//;s/].*//' <<<$str
-sharp
awk -F'[][]' '{print $2}' <<<$str

2. How can I tell that the string fetched in 1 contains behind or diverged?

[[ $str =~ "behind" || $str =~ "diverged" ]] && echo "" || echo ""
Menu