Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understand bash script syntax

What does the following bash syntax mean:

function use_library {
    local name=$1
    local enabled=1
    [[ ,${LIBS_FROM_GIT}, =~ ,${name}, ]] && enabled=0
    return $enabled
}

I don't particularly understand the line [[ ,${LIBS_FROM_GIT}, =~ ,${name}, ]]. Is it some kind of regex or string comparison?

like image 241
Mark Avatar asked Apr 22 '26 11:04

Mark


1 Answers

This is a trick to compare variables and prevent a weird behaviour if some of them are not defined / are empty.

You can use , or any other. The main thing is that it wants to compare ${LIBS_FROM_GIT} with ${name} and prevent the case when one of them is empty.

As indicated by Etan Reisner in comments, [[ doesn't have empty variable expansion problems. So this trick is usually used when comparing with a single [:

This doesn't work:

$ [ $d == $f ] && echo "yes"
bash: [: a: unary operator expected

But it does if we add a string around both variables:

$ [ ,$d, == ,$f, ] && echo "yes"
$ 

Finally, note you can use directly this:

[[ ,${LIBS_FROM_GIT}, =~ ,${name}, ]] && return 0 || return 1
like image 127
fedorqui 'SO stop harming' Avatar answered Apr 24 '26 00:04

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!