String comparisons with test and brackets
test and [ are Bash built-ins that return a status rather than printing a Boolean. [ "$name" = "Ada" ] compares literal strings; -z tests an empty string and -n tests a nonempty string. Spaces around [ and ] matter because the opening bracket is a command name and the closing bracket is its final argument. Quote operands so empty values, spaces and wildcard characters remain one argument. Use = for portable string equality and != for inequality. == is also accepted by Bash test, but is not the portable choice.
Practical examples
Run each example separately in Bash 5.2 in a fresh empty practice directory. Tests use default shell options and C locale. Output is shown separately; do not enter it as code.
Compare strings
Expected stdout:
editEquality compares the string values.
Check empty values
label=''if test -z "$label"; then printf '%s\n' empty; filabel='daily report'if [ -n "$label" ]; then printf '%s\n' present; fiExpected stdout:
emptypresentQuoting preserves both empty and spaced operands.
Compare inequality
name='daily report'[ "$name" != 'weekly report' ]printf '%s\n' "$?"Expected stdout:
0The two strings differ, so the status is zero.
Common mistakes
[ -n $name ] with an empty value can become [ -n ], which tests the nonempty string -n and succeeds. Use [ -n "$name" ]. Avoid ambiguous multi-operand -a and -o forms; use separate tests.
Practice
Compare role=editor with admin; then test an empty label and a label containing a space. Print clear messages.
Next: Integer and file tests