22

shell 字符串比较与脚本 too many arguments 报错

 4 years ago
source link: http://www.cnblogs.com/operationhome/p/11831480.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、问题

最近在写 shell 脚本的时候,遇到了一些小问题,就是我在判断一个字符串是否为空的时候经常报下面的错,程序是正常执行了,但是有这个提示很蛋疼,下面就是看看是什么问题导致的?

[: too many arguments

二、问题解析

原始脚本

我的脚本是这样写的

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

运行后

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

第一个问题: -eq 是用于比较两个数字的,比较字符串要使用 ==

更改版本一 使用 "==" 进行比较

使用 "==" 进行比较,替换 -eq .

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

运行之后

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

还是有这个报错,但是经过我的测试发现,如果我们将 list 值设置为 没有空格的话,是不会出现这个问题。

更改版本二 使用 "==" 进行比较,更改变量的值

list 原来的值为: 1 2 4 ad 更改为 ad

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

运行之后

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

运行正常。

问题原因

问题是有空格导致的。但是经过我们的测试,发现,形如 adadad ,这种单单前后有空格的,是不会报错的,但是像 ad ad ,这种两个字符直接有空格的话,是会进行报错的。

三、问题解决

字符串判断

使用 == 进行判断字符串是否相等, 判断字符串是否为空的话用 -z 或者 -n

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

在进行字符串判断的时候使用 ""或者 ''.

  • '' :单引号不适合在引用变量做比较的时候使用。因为它会让变量拿不到值。
  • "" :适合在任何时候引用,引用变量以及不引用变量都可以使用。

示例:当我们的字符串必须包含空格的时候

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

我们可以在使用变量做比较的时候,在变量外使用双引号。

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK