3 ms·
I still use this hack without thinking about it in case the variable on the left is empty. But I suppose I should actually be quoting. [ $X == "hello" ] Wh
by mikedilger 6y ago
I still use this hack without thinking about it in case the variable on the left is empty. But I suppose I should actually be quoting.
[ $X == "hello" ]
When X is empty, it gives:
example.sh: line 5: [: ==: unary operator expected
So I fix it (apparently wrongly) with:
[ x$X == x"hello" ]
I'll make a point of doing this instead:
[ "$X" == "hello" ]
- koala_man 6y agoDefinitely quote. `[ x$X == x"hello" ]` may fail for a variety of different values of X like `*`, `Rocky_[1976].jpg`, `hello world` and `foo = xfoo -o bar` Quoting works in all those cases.
- naniwaduni 6y agoOf the listed, it should only actually fail on the ones with spaces in them (or rather, the ones that get split according to IFS).
- koala_man 6y agoWhether or not it should, it may fail for any kind of glob. This could be either because the glob ends up unintentionally matching something: $ var='*'; touch xfoo xbar $ [ x$var == x"hello" ] bash: [: too many arguments $ var="Rocky_[1976].jpg"; touch xRocky_7.jpg $ [ x$var == x"Rocky_[1976].jpg" ] (false, should be true) or because you have something like nullglob or failglob enabled: $ var="Rocky_[1976].jpg"; shopt -s nullglob $ [ x$var == x"hello" ] bash: [: ==: unary operator expected