Shell script if judgment statement error [: Two reasons of too many arguments

Source: Internet
Author: User

Shell script, if judgment statement error [: Too many arguments

I have encountered two situations:

1, the first situation is that the Internet, you can say, the string variable may exist in a space, shell resolution when it is considered to be more than one parameter, and then judge, you can not know what to get the value, for example:

Script ee.sh:

strings1= "Hello World" strings2= "Hello World"
if [$strings 1 = $strings 2]
Then
echo "STRINGS1 is same as STRINGS2"
Else
echo "STRINGS1 is different from STRINGS2"
Fi


Error in execution result:

Ee.sh:line 3: [: Too many arguments
STRINGS1 is different from STRINGS2

and automatically executes the statements in the Else branch.

The following statement would not be like this:

Script ee.sh:

strings1= "Hello World"
strings2= "Hello World"
If ["$strings 1" = "$strings 2"]
Then
echo "STRINGS1 is same as STRINGS2"
Else
echo "STRINGS1 is different from STRINGS2"
Fi

Execution result: STRINGS1 is same as Strings2


2, the second is my initial contact with the shell script, a lot of grammar rules are not familiar with the encounter, I write it as-multiple judgments:

Or, in the example above, change the second paragraph slightly:

Script ee.sh:

strings1= "Hello World"
strings2= "Hello World"
If ["$strings 1" = "$strings 2"-eq 1]
Then
echo "STRINGS1 is same as STRINGS2"
Else
echo "STRINGS1 is different from STRINGS2"
Fi

Execution results:

Ee.sh:line 3: [: Too many arguments
STRINGS1 is different from STRINGS2

This is written in the usual way, "$strings 1" = "$strings 2" to determine whether two strings are equal, and if the result of equality is true, and true is usually equivalent to 1 in the general language, and therefore compares this result with 1 ", In fact, in this logic, I ignore the "$strings 1" = "$strings 2" itself is a judgment condition, the execution result is true or false, without the need to judge the result whether it is 1.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.