Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script purpose of x in "x$VARIABLE" [duplicate]

Tags:

shell

unix

I'm peeking through some shell scripts - what's the purpose of the x in the comarison shcu as

 if [ "x$USER" != "x$RUN_AS_USER" ]; then
        su - $RUN_AS_USER -c "$CATALINA_HOME/bin/startup.sh"
 else
        $CATALINA_HOME/bin/startup.sh
 fi
like image 639
leeeroy Avatar asked Nov 26 '09 21:11

leeeroy


People also ask

What does X mean in shell script?

Bash Shell -x Option. Invoking a Bash shell with the -x option causes each shell command to be printed before it is executed.

What does X mean in Unix?

X is used to indicate all operating systems similar to Unix.

What is the significance of $? In script?

$? returns the exit value of the last executed command.

What does set X do Bash?

Bash provides the set command in order to enable or disable different features. The set -x command is used to debug bash script where every executed statement is printed to the shell for debugging or troubleshooting purposes.


1 Answers

It's a trick to ensure you don't get an empty string in the substitution if one of the variables is empty. By putting x on both sides it's the same as just comparing the variables directly but the two sides will always be non-empty.

It's an old kludge which made more sense when scripts were written as:

if [ x$USER != x$RUN_AS_USER ]

There if you just had $USER and it were empty then you could end up with

if [  != root ]   # Syntax error

With the x you get this, which is better:

if [ x != xroot ]

However, when the variables are quoted the x is unnecessary since an empty string in quotes isn't removed entirely. It still shows up as a token. Thus

if [ "$USER" != "$RUN_AS_USER" ]   # Best

is the best way to write this. In the worst case with both variables empty you'd get this which is a valid statement:

if [ "" != "" ]
like image 124
John Kugelman Avatar answered Nov 01 '22 02:11

John Kugelman