Skip to content
Brett edited this page Nov 24, 2021 · 7 revisions

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).

Related resources:

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally