最近在写 shell 脚本的时候,遇到了一些小问题,就是我在判断一个字符串是否为空的时候常常报下面的错,程序是正常执行了,可是有这个提示很蛋疼,下面就是看看是什么问题致使的?shell
[: too many arguments
个人脚本是这样写的bash
#!/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
是用于比较两个数字的,比较字符串要使用 ==
。code
使用 "==" 进行比较,替换 -eq
.ip
#!/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 值设置为 没有空格的话,是不会出现这个问题。string
list 原来的值为:1 2 4 ad
更改成 ad
class
#!/bin/bash list='ad' if [ $list == '' ] then echo "empty" else echo "not empty" fi
运行以后test
[root@wi-mi-2034 scripts]# bash test.sh not empty
运行正常。变量
问题是有空格致使的。可是通过咱们的测试,发现,形如 ad
和 ad
和 ad
,这种单单先后有空格的,是不会报错的,可是像 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