多个if语句和while循环在bash脚本中重新分配变量语法错误

时间:2017-11-29 14:31:05

标签: bash

  1. 这是我写的bash脚本出错了。意外令牌令牌'fi'附近的语法错误我指出了错误消息指向下面的行。我不确定为什么会出现这个错误。也许我在语法上犯了错误。请帮忙!
  2. 我在底部用其他语言编写了相同的逻辑,以便您更好地理解我的问题。我注意到在bash中使用if语句时有两种语法if [[ conditional statement ]]; thenif [ conditional statement ] then我也很想知道两者之间的区别是什么?谢谢你的帮助!

        #!/bin/bash
    
    
        groupadd SC001
        count=1
        userid=$(ls /home | wc -l)
        echo "##Total user is "$userid
    
        if [ $uesrid -lt 10 ] then
            while [ $count -lt 10 ] 
                do
                    useradd -m "sc"$count"_2018"
                    let "count+=1"
                done
        fi   <-----------------------------This is the line where error message pointing at lol
    
        count=10
        userid=$(ls /home | wc -l)
        if[ $uesrid -ge 10 ] then
            while [ $count -le 25 ] 
                do
                    useradd -m "sc"$count"_2018"
                    let "count+=1"
                done
        fi
    
    ################# Could be written in other language
    
        groupadd SC001
        int count = 1;
        int userid = userid=$(ls /home | wc -l);
        system.out.print("##Total user is "+userid);
    
        if (userid < 10){
            while (count < 10){
                useradd -m "sc"$count"_2018";
                count++;
            }
        }
    
    
    
        count=10;
        userid = userid=$(ls /home | wc -l);
        if (userid >= 10){
            while (count < 25){
                useradd -m "sc"$count"_2018";
                count++;
            }
        }
    

2 个答案:

答案 0 :(得分:4)

当您编写while循环时,您将do放在自己的行上。 if期望与then相同。

错:

if [ blah ] then

右:

if [ blah ]
  then

很多人觉得这样做很麻烦,所以如果你愿意,你可以用分号代替换行符。

if [ blah ]; then

答案 1 :(得分:0)

我找到了答案!我注意到没有流行的IDE用于bash脚本。但是,我找到了一个语法检查器!我从https://www.shellcheck.net/得到了帮助。我的所有错误都被突出显示并解释了为什么以及如何像IDE一样解决它们。现在它完美无缺。快乐!

#!/bin/bash

groupadd SC001
count=1
userid=$(find /home -maxdepth 1 -type d -printf '%f\n' | wc -l)
echo "##Total user is ""$userid"

if [ "$userid" -lt 10 ]; then
    while [ $count -lt 10 ] 
        do
            useradd -m "s"$count"_2018"
            ((count+=1))
        done
fi

count=10
userid=$(find /home -maxdepth 1 -type d -printf '%f\n' | wc -l)
if [ "$userid" -ge 10 ]; then
    while [ $count -le 25 ] 
        do
            useradd -m "s"$count"_2018"
            ((count+=1))
        done
fi
相关问题