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 really understand the line [[ ,${LIBS_FROM_GIT}, =~ ,${name}, ]]
. Is this some kind of regex or string comparison?
source to share
This is a trick for comparing variables and preventing strange behavior if some are undefined / empty.
You can use ,
or any other. The main thing is that he wants to compare ${LIBS_FROM_GIT}
with ${name}
and prevent the case when one of them is empty.
As Ethan Reisner points out in the comments, [[
has no problem with empty variable expansion. So this trick is commonly used when comparing to one [
:
This does not work:
$ [ $d == $f ] && echo "yes"
bash: [: a: unary operator expected
But that's the case if we add a line around both variables:
$ [ ,$d, == ,$f, ] && echo "yes"
$
Finally, note that you can use this directly:
[[ ,${LIBS_FROM_GIT}, =~ ,${name}, ]] && return 0 || return 1
source to share