dinkelk dinkelk - 3 months ago 5x
Bash Question

Should I use "test" or "[" "]" in POSIX shell?

I believe both of the following code snippets are valid in POSIX compliant shell:

Option 1:

if [ "$var" = "dude" ]
echo "Dude, your var equals dude."

Option 2:

if test "$var" = "dude"
echo "Dude, your var equals dude."

Which syntax is preferred and why? Is there a reason to use one over the other in certain situations?


There is no functional difference, making this a purely stylistic choice with no widely accepted guidelines. The bash-hackers wiki has an extended section on classic (POSIX-compliant) test, with a great deal of attention to best practices and pitfalls, and takes no position on which to prefer.

Moreover, the POSIX specification for test -- while it does mark a great deal of functionality obsolescent1 -- specifies neither form as preferred over the other.

One minor advantage to test is that it's less conducive to folks bringing in habits from other languages. For instance, it's a common error to write [$foo=1] rather than the correct [ "$foo" = 1 ], but folks aren't widely seen to write test$foo=1. Whether this minor advantage outweighs terseness, however, is very much open for individual judgment and interpretation.

[1] Such as -a, -o, ( and ), and any usage with more than four arguments (excluding the trailing ] on an instance started under the name [).