String comparison in bash script

I am learning bash scripts. I got a sample script below from the internet.

#!/bin/bash str="test" if [ x$str == x"test" ]; then echo "hello!" fi 

What is x on the fifth line ( x$str and x"test" )? x " x " have a special meaning?

+6
source share
2 answers

There is no special meaning, but if $str was empty, then

 if [ $str == "test" ] 

will replace anything in the test, and it will be like this:

 if [ == "test" ] 

which will be a syntax error. Adding X in front would resolve this, however, citing it like this

 if [ "$str" == "test" ] 

is a more readable and understandable way to achieve the same.

+9
source

To make sure that the left side of the expression in your example is not empty. If str not set, the condition would otherwise be [ == "test" ] , which would give an error.

Instead of using a single letter to make it non-empty, you can also put the variable in double quotes and skip x completely ( [ "$str" == "test" ] ).

+2
source

Source: https://habr.com/ru/post/900840/


All Articles