7 SC2268
Brett edited this page 2021-11-24 12:46:15 -08:00

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

Problematic code:

[ "x$pass" = "xswordfish" ]

test x"$var" = x 

Correct code:

[ "$pass" = "swordfish" ] 

test "$var" = ""

Rationale:

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.

Examples:

Bash 1.14 from 1992 incorrectly fails this test. This was fixed for Bash 2.0 in 1996:

var='!'
[ "$var" = "!" ]

Dash 0.5.4 from 2007 incorrectly passes this test. This was fixed for Dash 0.5.5 in 2008:

x='(' y=')'
[ "$x" = "$y" ]

Zsh (while not supported by ShellCheck) fixed the same problem in 2015.

Exceptions:

If you are targeting especially old shells, you can ignore this warning (or use a different letter).