2015-09-02 42 views
1

我正在编写一个shell脚本来创建一个用户并将它们添加到一个组中。我遇到了第17行的障碍,当我有一个错误,可以在这里看到http://imgur.com/XhNGIeW ,但一半的代码似乎是完美的(就添加用户而言),但任何人都可以帮助我这个谢谢。Linux shell脚本程序在29行后退出?

#!/bin/bash 
let repeat=1 
let counter=0 
while [ $repeat -eq 1 ]; 
     do 
     echo "Please enter the username for the created user" 
     read username 
     sudo useradd -m $username 
     echo "" 
     sudo passwd $username 
     let counter=$counter+1 
     while [ $repeat -eq 1 ]; 
       do 
       echo "please enter the name of the group to put the user into" 
       read group 
       if [ $(getent group $group) ]; then #line 17 
         sudo usermod -G $group,sudo $username 
         let repeat=0 
       else 
         echo "The group "$group$" does not exist on our system" 
         echo "Do you want to create it as a new group (y)" 
         read input 
         if [ $input == "y" ]; then 
           sudo groupadd $groups 
           sudo usermod -G $group,sudo $username 
           let repeat=0 

         fi 

       fi 

     done 
     echo $username" has beem added to the group "$group 
    done 

    echo "You have now created "$counter" new user(s) and have added them to their new group(s)" 
+0

哪一条是17号线? –

+1

为什么你有'''''?只有''''应该足以识别空字符串? –

回答

0

如果组的名称是无效的,getent group $group将不返回任何 输出,使线17将等同于:

if [ != '' ]; then 

!=操作前,操作后比较字符串。如果 所需的字符串缺少一个,壳报告错误:

[: !=: unary operator expected 

如果你想检查一个有效的组,你可以简单地检查一些输出 返回:

if [ $(getent group $group) ]; then 
+0

只要它到了,“你想创建它作为一个新的组”它无缘无故关闭终端? – blawrence

+0

@blawrence对于第22行中的'['命令:'if [[$ input ==“y”]]'',有太多的参数。你只需要'如果[$ input == y]'。 –