0

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 then based on his answers adding him/her to a group. Can anyone help?

closed as too broad by Kiwy, Stephen Kitt, user34720, Jeff Schaller, Anthony Geoghegan Jun 26 '18 at 10:59

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    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. – Kiwy Jun 26 '18 at 7:07
1

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
  • The line numbers you've added make it impossible for anyone to copy'n'paste your script. Please could I suggest you remove them. – roaima Jun 26 '18 at 9:48
  • The thing is that I do not need to create users. All users are already created. – tera_789 Jun 26 '18 at 17:01
0

You can add a line in your script to find out who is executing the script using

user=$(whoami)
echo $user

If the script needs to be run with sudo, whoami will always give root as user , so you need to use $SUDO_USER variable

user=$SUDO_USER
echo $user

If the user uses, su - and then executes the script, then the above solutions will not work, use who am i

user=$(who am i | awk '{print $1}')
echo $user
  • Yes you are right, had not tried that ,will add that to the answer @roima thanks – Arushix Jun 26 '18 at 9:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.