8

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?

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Looks like the example was taken from the testcases used to test a fresh bash compile, only reference I've found to the prepend x method was arguing that the "" method was better and whether the test case should be changed.
What is better is a matter of taste -- I have seen the x method a few places, and im sure there are places in pipelines or deep substitutions where it would actually make the code more readable -- however for simple cases like the one above, the "" is intuitively understood and would never have raised a question.
Yeah, I didn't say it was my argument, I said it was the argument on the GNU bash mailing list.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.