2015-09-02 41 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]'。 –