Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string comparison in bash script

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?

like image 216
Akira Noguchi Avatar asked Nov 05 '11 13:11

Akira Noguchi


People also ask

Can you compare strings in bash?

The need to compare strings in a Bash script is relatively common and can be used to check for certain conditions before proceeding on to the next part of a script. A string can be any sequence of characters. To test if two strings are the same, both strings must contain the exact same characters and in the same order.

How do I compare two string variables in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.


1 Answers

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.

like image 93
Soren Avatar answered Oct 01 '22 16:10

Soren