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
Share:
7,108

Related videos on Youtube

tera_789
Author by

tera_789

Beginner in programming starting out with Visual Basic (Visual Studio 2015).

Updated on September 18, 2022

Comments

  • tera_789
    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?

    • S edwards
      S edwards almost 6 years
      Welcome on StackExchange Unix&Linux. Please take the time to read the tour. Do you have some example of what you did ? on this site we expect some proof of work please edit your question to add some more context to it.
  • Arushix
    Arushix almost 6 years
    Yes you are right, had not tried that ,will add that to the answer @roima thanks
  • roaima
    roaima almost 6 years
    The 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
    tera_789 almost 6 years
    The thing is that I do not need to create users. All users are already created.
  • Admin
    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 even if grep -qF "$USERGROUP". Unfortunately in both cases a USERGROUP=fred would match to freddie so it's a poor condition check anyway