예기치 않은 토큰 'else' 근처에 구문 오류가 있으며 잘못된 들여쓰기가 있을 수 있습니다.

예기치 않은 토큰 'else' 근처에 구문 오류가 있으며 잘못된 들여쓰기가 있을 수 있습니다.

사용자를 생성한 다음 사용자에게 방금 생성한 사용자를 할당할 그룹 이름을 묻고 마지막으로 다른 사용자를 생성할지 묻는 셸 스크립트를 작성하려고 합니다.

Line 21: 예기치 않은 토큰 "else" 근처에서 구문 오류가 계속 발생합니다. Line 21 "else"

#!/usr/bin/env bash

anotherUser() {
     read -p "Do you want to add another user? [y/n] yn"
     if [[ $yn = *[yY]* ]]; then
        checkUser
     fi
     exit
}
checkUser() {
while :
     do
      read -p "Enter username you would like to generate: " userName
      read -s -p "Enter password : " userPass
      if id "$userName" >/dev/null; then
         echo "Sorry user exists"
         anotherUser 
      else
         echo adduser "$userName"
         printf "User %s has been added\n" "$userName"
      else
         read -p "Enter group you want to assign user to: " userGroups
         useradd -G "userGroups" "$userName" &&
         printf "User %s has been added\n"  "$userName"
            fi
            break
    done
            exit
     fi
done
}
checkUser

답변1

이건 어때:

#!/usr/bin/env bash

checkUser() {
    while true; do
       read -p "Enter username you would like to generate: " userName
       if id "$userName" >/dev/null 2&>1; then
          echo "Sorry user exists"
       else
          read -s -p "Enter password : " userPass
          echo adduser "$userName"
          printf "User %s has been added\n" "$userName"
          read -p "Enter group you want to assign user to: " userGroups
          useradd -G "userGroups" "$userName" &&
          printf "User has been added to group %s\n"  "$userGroups"
       fi
       read -p "Do you want to add another user? [y/n] " yn
       if [[ $yn = *[nN]* ]]; then
          break
       fi
    done
}
checkUser

답변2

이것은 작동합니다:

#!/bin/bash

anotherUser() {
     read -p -r "Do you want to add another user? [y/n] yn" yn
     if [[ $yn = \*[yY]\* ]]; then
        checkUser
     fi
     return 1
}

checkUser() {
while :
     do
      read -p -r "Enter username you would like to generate: " userName
      if id "$userName" >/dev/null; then
         echo "Sorry user exists"
         anotherUser 
      else
         echo adduser "$userName"
         printf "User %s has been added\n" "$userName"
         read -p -r "Enter group you want to assign user to: " userGroups
         useradd -G "$userGroups" "$userName" &&
         printf "User %s has been added\n"  "$userName"
        return 0
     fi
done

}

checkUser

관련 정보