Script users

mirror25

New Member
Joined
Mar 2, 2019
Messages
1
Reaction score
0
Credits
0
Good morning, I have a problem with the following shell script.
Do I need to ask again if the user is already registered in the system? If I put a pause after <echo "already exists"> it gives me an error, and if I put an output, it leaves the script completely. I've also tried to put a real one after <echo -n "Do you want to enter a user? (Y / N):"; read answer> but it does not work either

The purpose of the script is to request a username, if it does not exist, and then create it. But if it already exists ask for another name.

Thank you.




Code:
#!/bin/bash
echo -n "Do you want to enter a user? (y/N): "; read answer

 if [ $answer = 'y' ]; then
   echo "Enter the user: "
    read USER
    if grep -qi "^$USER:" /etc/passwd
    then
    echo "already exists"
    else
    echo "does not exist"
    fi
 elif
     [ $answer = 'N' ]; then
 exit
fi
 
Last edited:


Well, why not put your entire script into a loop?
But it seems a bit odd asking if the user wants to enter a username first. The best bet would be to assume that they do - otherwise they wouldn't have ran the script.
Also, don't use $USER for the username - because I'm fairly certain there is already a global environment variable called $USER. I don't know what effects using the same variable name in your script could have.

Perhaps use something like $username ( in lowercase) instead.

So I'd do it something like this:
Code:
#!/usr/bin/env bash
while true
do
  echo "Enter the new username: "
  read username
  if grep -qi "^$username:" /etc/passwd
  then
   echo "ERROR: User $username already exists"
  else
   echo "$username does not exist - TODO: create a new user called $username"
  fi

  echo -n "Do you want to enter another user? (y/N): ";  read answer

  if [ $answer != 'y' ]; then
     exit
  fi
done

That way, your users can get straight down to business and enter their first user-name straight away.
If the user name does exist - you output an error message.
If the user name does not exist - you can create a new user. I'll leave you to work out how you'll do this.
And whatever the result of the test on the usernamme, you simply ask whether the user wants to try to add another username.
If they answer 'y' - we reiterate through our infinite loop.
If they respond with anything else - we exit.... Simple!
 
Last edited:
Or was that a snippet from a bigger script?
 

Members online


Top