Compared with the script shell string too many arguments error

First, the problem

Recently when writing shell scripts, encountered some minor problems, it is what I determine whether a string is empty frequently reported the following error, normal procedure is performed, but this tip is very boring, here is a look What caused the problem?

[: too many arguments

Second, the problem resolved

The original script

My script is written

#!/bin/bash
list='1 2 4 ad'
if [ $list -eq  '' ]
then
    echo "empty"
else
    echo "not empty"
fi 

After running

[root@wi-mi-2034 scripts]# bash test.sh 
test.sh: line 3: [: too many arguments
not empty

The first question: -eqis used to compare two numbers, comparing strings to use ==.

Changing a version using the "==" to compare

Use "==" compares replaced -eq.

#!/bin/bash
list='1 2 4 ad'
if [ $list ==  '' ]
then
    echo "empty"
else
    echo "not empty"
fi 

After running

[root@wi-mi-2034 scripts]# bash test.sh 
test.sh: line 3: [: too many arguments
not empty

Still have this error, but after my tests found that if we set the value to the list with no spaces, then, will not have this problem.

Version two value changes using the "==" to compare the variables change

The original list of values: 1 2 4 adChangead

#!/bin/bash
list='ad'
if [ $list ==  '' ]
then
    echo "empty"
else
    echo "not empty"
fi 

After running

[root@wi-mi-2034 scripts]# bash test.sh 
not empty

Operating normally.

problem causes

The problem is caused by a space. But after our tests, found that the form adand adand ad, just before and after such a space is not being given, but like ad adthis direct two characters with spaces, it would be incorrect report.

Third, the problem is solved

Analyzing string

Used ==for determining whether the strings are equal, it determines whether the string is empty, the use -zor-n

== :判断字符串是否相等
-z :判断 string 是否是空串
-n :判断 string 是否是非空串

In performing the string is determined when the use of '' or ''.

  • '': Is not suitable for use in single quotation marks when referring to the variable being compared. Because it will not get the value of the variable.
  • "": For reference at any time, without reference variables and reference variables can be used.

Example: When our string must contain spaces

#!/bin/bash
list='1 2 4 ad'
if [ $list ==  '' ]
then
    echo "empty"
else
    echo "not empty"
fi 

We can do when using variable comparison, use double quotes around the variable.

#!/bin/bash
list='1 2 4 ad'
if [ "$list" ==  '' ]
then
    echo "empty"
else
    echo "not empty"
fi 

Guess you like

Origin www.cnblogs.com/operationhome/p/11831480.html