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?
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.
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.
$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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With