I'm studying bash scripts. I got the sample script below from the web.
#!/bin/bash
str="test"
if [ x$str == x"test" ]; then
echo "hello!"
fi
What is x on fifth line(x$str and x"test")?
Does "x" have special meaning?
No special meaning, but if $str was empty, then the
if [ $str == "test" ]
would result in a substitution of nothing into the test and it would be like this
if [ == "test" ]
which would be a syntax error. Adding the X in front would resolve this, however quoting it like this
if [ "$str" == "test" ]
is a more readable and understandable way of achieving the same.
It's to make sure that the left side of the expression in your example is not empty. If str was not set, the condition would otherwise be [ == "test" ] which would give an error.
Instead of using an single letter to make it not-empty, you could also put the variable inside double quotation characters, and skip the x completely ([ "$str" == "test" ]).