How to define a users group using bash scripting?
7,108
I also created a simple script.
Below script is creating a new user on the system.
I'm very glad if you can use it as a reference.
Set the group name to VALIDGROUPS variable beforehand and
select it at the time of execution.
1 #!/bin/bash
2
3 VALIDGROUPS="GROUP1, GROUP2, GROUP3"
4
5 printf "Add your account on this system\n\n"
6 printf "Enter your name here, No space allowed for your user name : "
7 read USERNAME
8
9 printf "Valid user groups are $VALIDGROUPS Choose select one: "
10 read USERGROUP
11
12 grep $USERGROUP /etc/group 2>&1>/dev/null
13 if [ $? != 0 ]
14 then
15 printf "Group Name you entered $USERGROUP is not valid\n"
16 printf "Creating Abort!\n"
17 exit 1
18 else
19 useradd -g $USERGROUP -d /home/$USERNAME -s /bin/bash -m $USERNAME
20 passwd $USERNAME
21 fi
22
23 id $USERNAME
24
25 printf "done!\n"
26
27 exit 0
Related videos on Youtube
Author by
tera_789
Beginner in programming starting out with Visual Basic (Visual Studio 2015).
Updated on September 18, 2022Comments
-
tera_789 over 1 year
I am having hard time adding a user to a group in script.
For example, i have a script that asks user to answer several questions, and if answers are correct, that user should be added to a certain group.
So I probably need a way to somehow identify which user is answering questions (there are multiple users) and based on his answers add him/her to a group.
Can anyone help?
-
Arushix almost 6 yearsYes you are right, had not tried that ,will add that to the answer @roima thanks
-
roaima almost 6 yearsThe line numbers you've added make it impossible for anyone to copy'n'paste your script. Please could I suggest you remove them.
-
tera_789 almost 6 yearsThe thing is that I do not need to create users. All users are already created.
-
Admin almost 2 years@RicarHincapie it's a no-op except that the match result (yes/no) is used on the subsequent line. The two lines could have been written
if grep -F "$USERGROUP" >/dev/null 2>&1
or evenif grep -qF "$USERGROUP"
. Unfortunately in both cases aUSERGROUP=fred
would match tofreddie
so it's a poor condition check anyway