Linux – Learn bash script syntax

Learn bash script syntax… here is a solution to the problem.

Learn 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 [[ ,${LIBS_FROM_GIT}, =~ ,${name}, ]] line. Is it some kind of regular expression or string comparison?

Solution

This is a trick to compare variables and prevent some of them from being undefined/null strangely.

You can use , or any other. Mainly it wants to compare ${LIBS_FROM_GIT} and ${name} and prevent a case where one of them is empty.

As Etan Reisner points out in his comment, [[ There is no empty variable expansion problem. 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 if we add a string around both variables, it will do so :

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

Finally, note that you can use this directly:

[[ ,${LIBS_FROM_GIT}, =~ ,${name}, ]] && return 0 || return 1

Related Problems and Solutions