1

I was looking at the source code of NodeSource's installer script for Node.js.

Everywhere in the code, when they want to compare two strings, they prepend X to both sides before comparing:

if [[ "X${NODENAME}" == "XNode.js 10.x" ]]; then

I was pointed to some questions on the network:

They all explain why this is necessary when comparing with [. But in this case, the comparison is with [[.

Is this technique really necessary for [[?

Pedro A
  • 3,989
  • 3
  • 32
  • 56
  • 1
    It's an example of [cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming). `[[ $NODENAME == 'Node.js 10.x' ]]` is perfectly safe (and a lot more readable). – pjh Jun 09 '22 at 00:00
  • 1
    I don't think this should be closed as duplicate. "Why prepend an x to comparisons" is not the same as "Do we need to prepend an x when comparing with [[". – CoffeeTableEspresso Jun 09 '22 at 13:55

1 Answers1

6

Credits to @danielhoherd, in a comment

No, it's not necessary.

In fact, this technique is outdated for [ as well, as explained in the SC2268 shellcheck rule:

Avoid x-prefix in comparisons as it no longer serves a purpose.

[...]

Some older shells would get confused if the first argument started with a dash, or consisted of ! or (. As a workaround, people would prefix variables and values to be compared with x to ensure the left-hand side always started with an alphanumeric character.

POSIX ensures this is not necessary, and all modern shells now follow suit.

[...]

Pedro A
  • 3,989
  • 3
  • 32
  • 56
  • Note the "results are unspecified" for more than 4 arguments in the linked POSIX spec. Avoiding `-a` and `-o` to combine larger groups of operators is part and parcel of staying clear of ambiguous cases (where `(` and `)` can be improperly parsed as test syntax rather than values). – Charles Duffy Jun 08 '22 at 21:19