PAUSE
ENCORE5
ENCORE
BOX
SOLUTION
GO
Let's write a shell script to add a user to the file /etc/group
This process consists of the following steps:
1. Prompt for the group name
2. Read the response
3. Check to see whether the specified group name exists;
if it does, obtain the group_id;
otherwise, set the group_id to 150
4. Prompt for the user's id
4. Read the response
5. Append new entry to the file /etc/group
Please note, this exercise is for a user who has a good
understanding of Shell variables and commands. Those with
limited understanding should skip this example by typing a q.
A typical /etc/group file is shown above.
root:X:0:root,admin,oper
other:X:1:
cron:X:2:cron
bin:X:3:bin,who,dxu,dxu2
uucp::4:uucp
user:X:100:john:paul:jean:anna
demo::200:demo,vdemo,cdemo
Each line represents a group and is composed of:
group name,
group password,
group id, and
group members,
Note that a password may or may not be present !
Let's begin constructing the script.
First we need to prompt for the group name and read it.
Note, the function read reads one word into its argument.
echo "Please enter group name"
read gname
Check to see if the specified group name exists, and if so,
obtain the corresponding group id.
if grep "^$gname:" /etc/group > /dev/null
then
gid=`grep "^$gname:" /etc/group | cut -f3 -d:|tail -1`
Note, grep "^$gname:" /etc/group > /dev/null" says that grep will
look for the occurrence of the string representing the group name at
the beginning of the line in each entry of the file /etc/group.
If one is found, the result is sent to the null device.
cut -f3 -d: will look for the third field, with field delimiter :.
tail -1 filters out all but last line.
MOREC
If the specified group id does not exist, then set the group id to 150.
else
gid=150
fi
Now get the user's id (userid)
echo "Please enter the user's id"
read userid
Finally append an entry to the /etc/group file.
echo $gname::$gid:$userid >> /etc/group
If the group name was cti and the group id was 150
and the user id nicole, this would have the following effect on /etc/group:
root:X:0:root,admin,oper
other:X:1:
cron:X:2:cron
bin:X:3:bin,who,dxu,dxu2
uucp::4:uucp
user:X:100:john:paul:jean:anna
demo::200:demo,vdemo,cdemo
cti::150:nicole