0
#!/bin/sh
test="2"
if [ "$((test & 0x1))" != 0 ]; then
  echo "First bit is set"
else
  echo "First bit is not set"
fi

In this example, if statement contains double quotes and compared against an integer, this works well. But is this correct? Are double quotes right here? Works well even without the double quotes.

  • https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash#6697781 – Miguel Nov 23 '20 at 10:07
  • The duplicate's title talks about variables, but the discussion extends to any context where the shell evaluates a sequence of tokens. The *value* of quotes is to prevent the shell from doing whitespace splitting and wildcard expansion on the resulting value, which of course won't happen anyway if the value is a single number. But your expression should probably avoid `[` entirely and just use the arithmetic truth value; `if $((test & 0x1)); then` – tripleee Nov 23 '20 at 10:09
  • Thanks @tripleee I couldn't get much out from the references posted because i feel this is a different question. Can you please let me know why the code I posted works? – TheChosenOne Nov 23 '20 at 10:24
  • `2&1` is 0, and `0 != 0` is obviously false (`!=` does *string* comparison, btw. Doesn't matter here but normally you'd use `-ne` for integer comparison). – Shawn Nov 23 '20 at 10:57
  • Or, as suggested above, the arithmetic truth value, where `$((whatever))` is true if `whatever` does not evaluate to zero. – tripleee Nov 23 '20 at 10:58
  • Double quotes don't form strings. Whatever you are quoting is *already* a string, because the shell doesn't have separate data types: everything is a string. Double quotes simply provide automatic escaping of *every* character contained therein; `"foo"` is equivalent to `\f\o\o`. – chepner Nov 23 '20 at 16:23

0 Answers0