String comparison under linux

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/shuai0845/article/details/86532142

String comparison

Title: String comparison

Run the following command:

# str1="hello world"
# [ $str1 = "hello world" ] && echo 1 || echo 0

Originally thought outputs 1, the result is 0 output, may I ask why?

Run the following command:

# str2="jerry"
# [ $str2=="tom" ] && echo 1 || echo 0

Originally thought outputs 0, the result is 1 output, may I ask why?

answer:

  1. For the test of time strings, string variables should generally will again be compared after double quotes, or if the string contains characters such as spaces syntax error occurs. So the question should read:
# str1="hello world"
# [ "$str1" = "hello world" ] && echo 1 || echo 0 
# 1
  1. String test may be used =, ==or !=to compare two strings are the same or different, but it should be noted that the comparison must sign both ends spaces, or judgments logic errors - even if the syntax is no problem, but the results still may be incorrect judgment . So the question should read:
# str2="jerry"
# [ $str2 == "tom" ] && echo 1 || echo 0
# 0

Guess you like

Origin blog.csdn.net/shuai0845/article/details/86532142