3

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?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Mark
  • 6,052
  • 8
  • 61
  • 129
  • The `enabled` local is entirely unnecessary here. Simply having the last line be `[[ ,${LIBS_FROM_GIT}, =~ ,${name}, ]]` would have the same effect on the return value. – Etan Reisner Dec 15 '14 at 17:24

1 Answers1

4

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
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    `[[` doesn't have empty variable expansion problems. Ah, but an empty pattern will always match. – Etan Reisner Dec 15 '14 at 17:22
  • Good point, @EtanReisner . I included this into my answer, thanks. – fedorqui Dec 15 '14 at 17:24
  • 1
    No need for the `&& ...` bit at all. Those are the return values you get anyway. – Etan Reisner Dec 15 '14 at 17:27
  • Also, in the `[[` version the only thing that the commas are protecting from (as far as I can see) is an empty `name` which would seem to be more clearly handled by using an explicit test but . – Etan Reisner Dec 15 '14 at 17:40
  • Note that the commas make it work if either string is empty, but not if either contains spaces. Double-quoting the strings is a much better way to do this. – Gordon Davisson Dec 15 '14 at 18:25