Create script to add user and create directory

first off let me introduce myself. My name is Eric and I am new to linux, I am taking an advanced linux administration class and we are tasked with creating a script to add new users that anyone can run, has to check for the existence of a directory. if the directory does not exist then it has to be created. if it doe then it has to just proceed with the new user addition.

  1. The problem statement, all variables and given/known data:

how do i get this script to be able to create the directory if it does not exist?
or how do i get this script to run as root?
thanks in advance

  1. Relevant commands, code, scripts, algorithms:
    i have the script partially written i have rudimentary if/then/else statement where the first line reads:
echo "What department are you assigned to?"
read department     # $department
sleep 2
echo "you are assigned to the: $department"
sleep 7
clear

if [ -d /home/timberwolves/$department ]
then 
         echo "directory exists"
         sleep 3
         echo "what is your first name"
         read FirstName    # $FirstName
         sleep 2
         clear
         echo "what is your last name?"
         read LastName     # $LastName
         echo "You entered: $LastName"
         sleep 2
         clear
         echo "Please type your password (must be at least  characters)"
         read password      # $password
         sleep 2
         clear
         echo "The password you chose is: $password"
         sleep 7
         clear
         echo "Your login name will be: $FirstName"
         sleep 2
         clear
         echo "Your home directory will be: /home/timberwolves/$department/$FirstName
          sleep 7
          clear
else
mkdir -p /home/timberwolves/$department
         echo "what is your first name"
         read FirstName    # $FirstName
         sleep 2
         clear
         echo "what is your last name?"
         read LastName     # $LastName
         echo "You entered: $LastName"
         sleep 2
         clear
         echo "Please type your password (must be at least  characters)"
         read password      # $password
         sleep 2
         clear
         echo "The password you chose is: $password"
         sleep 7
         clear
         echo "Your login name will be: $FirstName"
         sleep 2
         clear
         echo "Your home directory will be: /home/timberwolves/$department/$FirstName
          sleep 7
          clear
fi
  1. The attempts at a solution (include all code and scripts):
    google searches

  2. Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):
    ECPI college or technology in virginia beach VA, Mr. Blow CIS305 advanced UNIX administration.

we do not have a direct link to the course

Note: Without school/professor/course information, you will be banned if you post here! You must complete the entire template (not just parts of it).

Thank you. :slight_smile:

The if-statement actually looks correct. What directory are you checking for? Make sure the directory is being typed in letter-for-letter. Also remember that filenames and directory names are case-sensitive.

in this first section of the code:

echo "What department are you assigned to?"
read department # $department
sleep 2
echo "you are assigned to the: $department"
sleep 7
clear

the variable $department

is the directory that the script will be looking for. if the directory exists then it will pass the if/then/else question and proceed to create the user. if it fails the script is supposed to create the directory that the user entered. my problem is getting the script to create the directory with out being logged in as root.

I know that. And I noted that if statement looks like it should do so.

Which is why I asked what, exactly you were typing into it, and also asked you to make sure you were typing it in letter for letter, and asked you if you were aware these paths were case-sensitive.

sorry for the confusion. the if statement works correctly if the directory does exist it says so and if it does not it does attempt to create the directory but i get the error
"mkdir: cannot create directory '/home/timberwolves/coaches': Permission denied"

then it proceeds with the if statement for failing the check.

It means what it says; permission denied.

Try

echo $USER
ls -ld /home/timberwolves

to see what permissions the directory has right now and whether it belongs to the right users/groups. It will have to be writable by you for you to create a new directory in it.

This script isn't being run under a different user than you is it?

at the moment no it is not being run under a different user than me. im not sure what my instructor will have us do to run it.

thanks

---------- Post updated at 05:56 PM ---------- Previous update was at 05:53 PM ----------

thank you for pointing out that i needed to change the folder permissions for timberwolves. this fixed my issue.

Couple of thoughts. Once you find that a department doesn't exist and create the directory for, it you may wish to create a group for it with 'groupadd'. Then set the GID to the newly created group.

A similar situation should be done for the user directory although you should create the directory with 'useradd'. 'useradd -g GROUP' will make sure the directory has the correct GID. Use the '-K UMASK=026' to make sure newly created files have the correct permissions. You'll have to look up how UMASK works. In this environment you may prefer 027 for more security.

A better way to handle the departments would be to create a list of valid existing departments. It would reduce spelling errors. The last option in the list could be "(N)ew department".

#!/bin/ksh
# root check code below
#deptroot=/home
deptroot=/home/wolverines
i=0
dept=()
echo "Department:"
find $deptroot -maxdepth 1 -type d | sort | while read x ;do
    bn=$(basename "$x");
    dept[$i]="$bn"
    i=$(($i + 1))
    echo "$i) $bn"
done
echo ""
echo -n "Enter number of department or 'n' for new department: "
read ans
echo "${dept
[*]}"
if [[ "$ans" =~ ^[0-9]+$ ]]; then
    echo "Numeric $ans $i"
    if [ $ans -lt $i ]; then 
       echo "In range"
       d="${dept[$(($ans - 1))]}"
       echo "Department: $d"
    fi
elif [ "$ans" == "n" ]; then
    echo "Prompt for new department"
    # assign d=DEPARTMENT
    # make sure it doesn't exist.. if exists exit
    # groupadd $d
    # mkdir "$depthome/$d"
    # chgrp $d "$depthome/$d"
else
    echo "bad input"
    exit 1
fi

Output Example:

$ ./test.sh 
Department:
1) History
2) Math
3) PhysEd
4) Science
5) Zoology

Enter number of department or 'n' for new department: 3
History Math PhysEd Science Zoology
Numeric 3 5
In range
Department: PhysEd

Sorry but I had to use KSH as BASH has a bug with pipes and while loops spawning subprocesses. BASH can't see what happened in the loop after the loop.

Lastly I'd add a check for the user ID at the beginning of your script.

if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

Only people with root access should be able to run any of this.

Lastly I'd add a check for the user ID at the beginning of your script.

if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

Only people with root access should be able to run any of this.
[/quote]

thanks i actually did this a couple of nights ago before i looked back at this thread.

as far as the departments go. as far as i know this script (unless my instructor takes it and uses it for future classes) is only going to be used by me for this one class. thank you for your help and direction.

now i do have another question though.

i have read on another forum for using a script to check if a user exists or not and this is what i have found:

$ egrep -i "^username" /etc/passwd

this is how i have it in my script:

/bin/egrep -i $UserName /etc/passwd
if [ $? -eq 0 ]
then
echo "User $UserName exists in /etc/passwd!"
else
echo "User $UserName does not exist in /etc/passwd!"
useradd -u 2000 $UserName
fi

my question is how do i get the little up arrow in the ("^username") to appear in vi editor?

or is my statement all wrong?

thanks

egrep -q "^$username:" /etc/passwd
if [ $? -eq 0 ]; then
    echo "found"
fi

I don't understand your question about the carat character. '^' can be inserted like any other character. In VI you hit 'i' to insert and then <shift 6> on a US keyboard.

I added ':' character to the end of the match to make sure it is an exact match. For instance "^Joe" can match "Joe", "Joe2", or "Joe_38933". "^Joe:" will only match user "Joe".

1 Like

Thank you that is what i was looking for (the keyboard shortcut). man have i had a long day it was only after you said <shift 6> that i saw the character there on the keyboard when i looked for it before posting to this site. man i feel so dumb at the moment haha.

thank you i will do this as you said.

again thank you for your assistance!

---------- Post updated 03-31-11 at 11:43 AM ---------- Previous update was 03-30-11 at 08:54 PM ----------

my next problem is to create a counter for the UID when i add a user this is what i have currently without the counter

/bin/egerp -i "^$UserName:" /etc/passwrd
if [ $? -eq 0 ]
then
echo "User $UserName exists in /etc/passwd!"
else
echo "User $UserName does not exist in /etc/passwd!"
useradd -u 2000 $UserName

now what i am thinking is something along the lines of this:

/bin/egerp -i "^$UserName:" /etc/passwrd
if [ $? -eq 0 ]
then
echo "User $UserName exists in /etc/passwd!"
else
echo "User $UserName does not exist in /etc/passwd!"
userid=2000
while test $userid -le 3000
do
echo $userid
userid="expr $userid+1"
done
useradd -u $userid $UserName

does this look correct?

thank you

'useradd' takes care of all that. It will also add the default directory and files in the new home directory and add the appropriate entries into /etc/passwd and /etc/shadow. No need for a counter. See previous comments for more information.

If you have to use a counter, these constructs will work also.

i=$userid
i=$(($i + 1))
#OR
let i=$userid
let i=++i;

But, then you'll have to find the highest UID and GID values in /etc/passwd for regular users. That will involve reading /etc/login.defs to get UID_MIN, UID_MAX, GID_MIN, GID_MAX and reading all of /etc/passwd for maximum valid UID and GID values. It's just not worth it. 'useradd' is much easier. To create password run 'passwd $user' after 'useradd'. So that's...

# if $dept doesn't exist
#   create new group with 'groupadd'
#   gid = dept's GID
#   create dir for dept
#   'chgrp' for dir of dept
# else
#   gid = dept's GID
# fi
useradd -m -d "/home/$dept/$user" -g $gid -K UMASK=026
passwd $user

i came to the same conclusion about it being a waste of time. thank you

i did have the useradd and the groupadd in my script so i guess that will have to do.

thank you for your help