Find the answer to your Linux question:
Results 1 to 4 of 4
Below is part of a script I am writing. I am trying to create better loops in the script so that for example if a field is left blank or ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    aic
    aic is offline
    Just Joined!
    Join Date
    Jun 2013
    Posts
    5

    Loop to prevent script from going back to main menu


    Below is part of a script I am writing. I am trying to create better loops in the script so that for example if a field is left blank or the username already exists below, the script does not return to the main menu and allows the user to attempt to put in another username and password (staying on option 1). Could someone show me how this would look? Thanks.

    RUNSCRIPT="YES"
    while [[ $RUNSCRIPT = "YES" ]]
    do

    case $choice in
    1) read -p "Enter new username: " username
    read -s -p "Enter new password: " password
    EmptyTest $username
    Ret1=$?
    EmptyTest $password
    Ret2=$?
    if [[ $Ret1 -eq 1 || $Ret2 -eq 1 ]]
    then
    echo ""
    echo "Field(s) blank!"
    else


    egrep "^$username" /etc/passwd >/dev/null

    if [ $? -eq 0 ]; then
    echo ""
    echo "$username exists!"
    else
    read -p "Password encrypted? (Y or N) " YesNo
    fi
    fi
    YN=`echo $YesNo | tr [:lower:] [:upper:]`
    case $YN in
    Y) useradd -p `openssl passwd -1 -salt 9Qj/F.Xw $password` $username # Creates a new username and an encrypted password
    echo "New user $username created with encrypted password!"
    ;;
    N) useradd -p $password
    $username
    echo "New user $username created!"
    ;;
    *) echo "Invalid choice, please try again." ;;
    esac ;;


  2. #2
    Linux Enthusiast
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    581
    You supplied the code fragment:
    Code:
    RUNSCRIPT="YES"
    while [[ $RUNSCRIPT = "YES" ]] ; do
    
        case $choice in
            1)  read -p "Enter new username: " username
                read -s -p "Enter new password: " password
                EmptyTest $username
                Ret1=$?
                EmptyTest $password
                Ret2=$?
                if [[ $Ret1 -eq 1 || $Ret2 -eq 1 ]] ; then
                    echo ""
                    echo "Field(s) blank!"
                else
                    egrep "^$username" /etc/passwd >/dev/null
                    if [ $? -eq 0 ] ; then
                        echo ""
                        echo "$username exists!"
                    else
                        read -p "Password encrypted? (Y or N) " YesNo
                    fi
                fi
                YN=`echo $YesNo | tr [:lower:] [:upper:]`
                case $YN in
                    Y)  useradd -p `openssl passwd -1 -salt 9Qj/F.Xw $password` $username # Creates a new username and an encrypted password
                        echo "New user $username created with encrypted password!"
                    ;;
                    N)  useradd -p $password $username
                        echo "New user $username created!"
                    ;;
                    *) echo "Invalid choice, please try again." ;;
                esac
    As you can see you only supplied a fragment of the code the case and while are not complete. Also "choice" is never provided with a value.
    You ask if the password was encrypted and then encrypt that on and uses the clear password as an encrypted password.

    Also the "useradd" that you used does not create a home directory for the account.



    You also might like looking at this code to determine what it is doing:
    Code:
    RUNSCRIPT="YES"
    while [ $RUNSCRIPT = "YES" ] ; do
        read -p "Enter new username: " username
        read -s -p "Enter new password: " password
        if [ "$username" == "" -o "$password" == "" ] ; then
            echo -e "\nERROR: You must supply both a user name and a password."
            contine
        fi
        if [ $(grep -c "^$username:" /etc/passwd) -gt 0 ] ; then
            echo -e "\nERROR: The user already is in use"
            conitnue
        fi
        read -p "Password encrypted? (Y or N) " YesNo
        case "${YesNo}" in
            [Nn]*)  password="$(openssl passwd -1 -salt 9Qj/F.Xw $password)" ;;
        esac
        if useradd -p $password  $username; thne
            echo -e "\nCreated a new account for username: ${username}"
            RUNSCRIPT="NO"
        else
            echo -e "\nError: unable to create a new account for username: ${username}"
        fi
    done
    Last edited by alf55; 07-12-2013 at 05:07 AM. Reason: Added comment about home directory

  3. #3
    aic
    aic is offline
    Just Joined!
    Join Date
    Jun 2013
    Posts
    5
    Basically I'm just trying to create a simple beginners script. Here is the complete code (I made the change to the useradd so that the home directory is created and reworded the encrypted password prompt to better explain what it's doing) :

    #!/bin/bash

    IsNumeric () # Functions
    {
    Numeric="Y"
    ans=$1
    len=`echo ${#ans}`
    for ((i=0; i<$len; i++))
    do
    val=`echo ${ans:$i:1}`
    echo $val | grep ^[0-9] > /dev/null
    RetVal=$?
    if [[ $RetVal -eq 1 ]]
    then
    Numeric="N"
    break
    fi
    done
    if [[ $Numeric = "Y" ]]
    then
    return 0
    else
    return 1
    fi
    }
    EmptyTest()
    {
    if [[ $1 = "" ]]
    then
    return 1
    else
    return 0
    fi

    }


    clear

    if [ "$(id -u)" != "0" ]; then
    echo "You must be logged in as root to run this administrative script." 1>&2 # Checks to verify user is root

    exit 1
    fi

    RUNSCRIPT="YES" # Allows script to run until user enters "N" for "No."
    while [[ $RUNSCRIPT = "YES" ]]
    do

    echo "1. Create User and Password" # Main Menu options
    echo "2. Reset User Password"
    echo "3. Password Management"
    echo "4. Create Group"
    echo "5. List Users"
    echo "6. Search for User"
    echo "7. View User's Activity"
    echo "8. Lock User"
    echo "9. Unlock User"
    echo "10. Delete User"
    echo "11. Delete Group"
    echo "12. Quit"
    read -p "Select a number option from the choices above: " choice # Reads user's numerical choice
    case $choice in
    1) read -p "Enter new username: " username
    read -s -p "Enter new password: " password
    EmptyTest $username # Calls a function to determine if field is empty.
    Ret1=$?
    EmptyTest $password
    Ret2=$?
    if [[ $Ret1 -eq 1 || $Ret2 -eq 1 ]] # If empty test returns 1 for error, notify the user.
    then
    echo ""
    echo "Field(s) blank!"
    else


    egrep "^$username" /etc/passwd >/dev/null

    if [ $? -eq 0 ]; then # Checks to see if username already exists.
    echo ""
    echo "$username exists!"
    else
    read -p "Would you like password to be encrypted? (Y or N) " YesNo
    fi
    fi
    YN=`echo $YesNo | tr [:lower:] [:upper:]`
    case $YN in
    Y) useradd -m -p `openssl passwd -1 -salt 9Qj/F.Xw $password` $username # Creates a new username and an encrypted password
    echo "New user $username created with encrypted password!"
    ;;
    N) useradd -m -p $password $username # Creates a new username and a plain-text password
    echo "New user $username created!"
    ;;
    *) echo "Invalid choice, please try again." ;;
    esac ;;
    2) read -p "Enter the username whose password you would like to reset: " username
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 1 ]; then
    echo "$username does not exist. Please enter a valid username."
    else
    passwd $username
    fi
    ;;

    3) read -p "Enter the username whose password you would like to manage: " username
    egrep "^$username" /etc/passwd >/dev/null # Checks to see if username exists
    if [ $? -eq 1 ]; then
    echo "$username does not exist. Please enter a valid username."
    else
    read -p "Enter the minimum number of days between password changes for this user: " mindays
    read -p "Enter the maximum number of days between password changes for this user: " maxdays
    IsNumeric $mindays
    Ret3=$?
    IsNumeric $maxdays
    Ret4=$?
    if [[ $Ret3 -eq 1 || $Ret4 -eq 1 ]]
    then
    echo "Field(s) not numeric!"
    else

    passwd -n $mindays -x $maxdays $username # Collects variables from the three prompts above and resets password settings for specified user
    read -p "Force user to change password at next login? (Y or N) " YesNo
    fi
    fi
    YN=`echo $YesNo | tr [:lower:] [:upper:]`
    case $YN in
    Y) passwd -e $username ;;
    N) echo "User will be asked to change their password in $maxdays days." ;;
    *) echo "Invalid choice, please try again." ;;
    esac ;;
    4) read -p "Enter the name of the group you would like to create: " groupname
    EmptyTest $groupname
    Ret1=$?
    if [[ $Ret1 -eq 1 ]] # If empty test returns 1 for error, notify the user.
    then
    echo "Field(s) blank!"
    else
    groupadd $groupname
    fi ;;

    5) echo "A. List users by name"
    echo "B. List users by primary group"
    echo "C. List users by secondary group"
    read -p "Enter the letter option from the choices above: " letterchoice
    case $letterchoice in
    a|A) cat /etc/passwd | cut -d: -f1 ;;
    b|B) . test1 ;; # Calls another script containing commands to view all users' primary groups.
    c|C) . test2 ;; # Calls another script containing commands to view all users' secondary groups.
    *) echo "Invalid choice, please try again." ;;
    esac ;;
    6) read -p "Enter the name of the user you would like to search for: " username
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 1 ]; then
    echo "$username does not exist! Please enter a valid username."
    else
    echo "A. Show username"
    echo "B. Show user id"
    echo "C. Show group membership"
    echo "D. Show home directory path"
    echo "E. Show login shell"
    read -p "Enter the letter option from the choices above: " letterchoice
    fi
    case $letterchoice in
    a|A) id -un $username ;;
    b|B) id -u $username ;;
    c|C) id -Gn $username ;;
    d|D) cat /etc/passwd | cut -f 1,6 -d: | grep "^$username" ;;
    e|E) cat /etc/passwd | cut -f 1,7 -d: | grep "^$username" ;;
    *) echo "Invalid choice, please try again." ;;
    esac ;;
    7) read -p "Enter the name of the user whose activity you would like to view: " username
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 1 ]; then
    echo "$username does not exist! Please enter a valid username."
    else
    read -p "How many iterations would you like to display? (Enter a numerical value) " numberiterations
    IsNumeric $numberiterations
    Ret1=$?
    EmptyTest $numberiterations
    Ret2=$?
    if [[ $Ret1 -eq 1 || $Ret2 -eq 1 ]]
    then
    echo "Not a numerical value or field(s) blank!"
    else

    top -n $numberiterations -U $username
    read -p "Would you like to kill this user's processes? (Y or N) " YesNo
    YN=`echo $YesNo | tr [:lower:] [:upper:]`
    fi
    fi
    case $YN in
    Y) pkill -u $username ;;
    N) echo "User will remain logged in" ;;
    *) echo "Invalid choice, please try again." ;;
    esac ;;
    read -p "Enter the username of the account you would like to lock: " username
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 1 ]; then
    echo "$username does not exist! Please enter a valid username."
    else
    passwd -l $username
    fi ;;
    9) read -p "Enter the username of the account you would like to unlock: " username
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 1 ]; then
    echo "$username does not exist! Please enter a valid username."
    else
    passwd -u $username
    fi ;;
    10) read -p "Enter the username of the account you would like to delete: " username
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 1 ]; then
    echo "$username does not exist! Please enter a valid username."
    else
    read -p "Leave user's home directory? (Y or N) " YesNo
    fi
    YN=`echo $YesNo | tr [:lower:] [:upper:]`
    case $YN in
    Y) userdel -r $username ;;
    N) userdel $username ;;
    *) echo "Invalid choice, please try again." ;;
    esac ;;
    11) read -p "Enter the name of the group you would like to delete: " groupname
    groupdel $groupname ;;

    12) echo "You have chosen to exit this program"; break ;;
    *) echo "That is not a valid choice. Try a number from 1 to 12." ;;
    esac
    read -p "Select another option? (Yes/No) " YesNo # Asks the user if they want to go back to main menu

    RUNSCRIPT=` echo $YesNo | tr [:lower:] [:upper:]`
    clear


    done

    The "Select another option?" prompt is made to come up after the completion of every case choice so that the script can be run again from the main menu. While I want to keep it that way, when there is an error like a username exists already I would like for it to loop back and re-echo for the user to put in another username and password to try rather than having them start from the main menu again. The rewritten code you posted is exactly what I'm looking for, I'm just trying to incorporate it into what I already have. Thanks.

  4. #4
    Linux Enthusiast
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    581
    The code:
    Code:
    egrep "^$username" /etc/passwd >/dev/null # Checks to see if username exists
    should be
    Code:
    egrep "^${username}:" /etc/passwd >/dev/null # Checks to see if username exists
    as a search for the username "bill" within a "/etc/passwd" that contains the following entries will all be matched.
    Code:
    bill:xxxxx:yyyy:...
    billiejean:zzzz:wwww:...
    billiondollors:aaa:ccc:...
    Billygoat:bbbb:cccc:...
    Why are you attempting to use the "EmptyTest" to see if variable is empty when there are several easier ways:
    • if [ -z $varnamegoeshere ] ; then
    • if [ "${variablenamegoeshere}" = "" ] ; then
    • [ "${variablenamegoeshere}" = "" ] && continue


    Also the use of the tags (inside open and closing square brackets) "code" and "/code" makes the code better as it retains indentation

    How about:
    Code:
    isIntegerNumber
    {
        return $(echo "$*" | grep -c '[^0-9]')
    }

    Your code is a lot larger than it needs to be. You need to learn more bash.

    For example:
    Code:
    echo "1. Create User and Password" # Main Menu options
    echo "2. Reset User Password"
    echo "3. Password Management"
    echo "4. Create Group"
    echo "5. List Users"
    echo "6. Search for User"
    echo "7. View User's Activity"
    echo "8. Lock User"
    echo "9. Unlock User"
    echo "10. Delete User"
    echo "11. Delete Group"
    echo "12. Quit"
    read -p "Select a number option from the choices above: " choice # Reads user's numerical choice
    Could simply be:
    Code:
    choices=(
                "Create User and Password" # Main Menu options
                "Reset User Password"
                "Password Management"
                "Create Group"
                "List Users"
                "Search for User"
                "View User's Activity"
                "Lock User"
                "Unlock User"
                "Delete User"
                "Delete Group"
                "Quit"
            )
    PS3="Select a number option from the choices above: "
    select choice in "${choices[@]}"; do
       [ "${choice}" != ""  ] && break 
    done

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •