if else 语句嵌套使用报错

用shell脚本执行了如下语句:

#!/bin/bash
read -p "please input your name : " -t 10 name
read -p "please input your number : " -t 10 number
read -p "please inlut your passwd : " -t 10 passwd
if [ !-z"$name"-a!-z"$number"-a!-z"$passwd" ]
then
    y=$(echo $number | sed 's/[0-9]//g')
    if [ -z"$y" ]
    then
        for ((i=1;i<=$number;i=i+1))
    do 
        /usr/sbin/useradd $name$i &>/dev/null
        echo $passwd | /usr/bin/passwd --stdin $name$1 &>/dev/null
    done
    else
        echo "Error!"
        exit 2
    fi
else
    echo "Error!!"
    exit 1
fi

想实现的效果:
第一个if else 语句;如果$name $number $passwd 中有一个为空,则提示:Error!并退出;如果都不为空则执行y=$(echo $number | sed 's/[0-9]//g')
第二个if else 语句:如果$y为空,则执行:for循环语句;如果不为空则提示:Error!并退出。
但是输入$name $number $passwd 为空之后,报错了,信息如下:

root@ubuntu:/home/baochunfen# bash for04.sh
please input your name : 
please input your number : 
please inlut your passwd : 
for04.sh: line 10: ((: i<=: syntax error: operand expected (error token is "<=")

恳请解答,谢谢各位大佬了

阅读 3.7k
2 个回答

if [ ! -z "$name" -a ! -z "$number" -a ! -z "$passwd" ]

加上空格。

bash 是依靠空格分隔的。[bash 的一个内置命令,其中的所有操作符和操作数都必须的这个命令的独立的参数。

没有空格,[ 这又一个参数。这要这个参数不空,返回就是真。在你这里这个参数一定不空。

bash

test expr
[ expr ]
Return a status of 0 or 1 depending on the evaluation of the conditional expression expr. Each operator and operand must be a separate argument. Expressions are composed of the primaries described above under CONDITIONAL EXPRESSIONS. test does not accept any options, nor does it accept and ignore an argument of -- as signifying the end of options.

......
[当为该命令提供了] 1 argument
The expression is true if and only if the argument is not null.

5.0.2测试没问题

bash 版本多少?

z"$name"-a!-z"$number"-a!-z"$passwd

你是不是这么写的?如果是的,那就这个错了
,注意分割符号 if [ ! -z "$name" -a ! -z "$number" -a ! -z "$passwd" ]

我一直以为是粘贴错误( ¨̮ )

推荐问题