0
#!/bin/bash

echo "Enter username: "
read username
sudo useradd "$username"

read -p "add to wheel group $username $foo? [yn]" answer
if [[ $answer = y ]] ; then
  sudo usermod -aG wheel "$username" && echo "$username is added to wheel group"
else echo "$username is not in wheel group"
fi

read -p "add password to $username $foo? [yn] " answer
if [[ $answer = y ]] ; then
   passwd $username
else echo "no passwd set to user $username"
fi

read -p "change user to $username $foo? [yn]" answer
if [[ $answer = y ]] ; then
        su $username && pwd
        else echo "user not changed to $username"
fi

in this part i am trying to change to a new user and run pwd. but script stops executing right after su $username. i want to run several commands inside a new user.

read -p "change user to $username $foo? [yn]" answer
if [[ $answer = y ]] ; then
        su $username && pwd
        else echo "user not changed to $username"
fi

script could be more clear but i just want to be able to run script that would continuously run in new user

  • AFIK, `su` is doing an implicit `exec`. You can't use it for your purpose. – user1934428 Nov 08 '22 at 06:21
  • thank you user1934428 . but what is a right way to do it then? – tryhardnoob Nov 08 '22 at 06:32
  • One possibility is to write the program in C instead of shell script. I think the `setuid` function should do the job. Or keep using shell and do kind of "continuation passing" style: Pass to `su` (using the [`-c` flag](https://manpages.org/su)) another shell script, which contains that part of the script which needs to be executed as the new user. – user1934428 Nov 08 '22 at 06:57
  • Do the answers to ["How do I use su to execute the rest of the bash script as that user?"](https://stackoverflow.com/questions/1988249/how-do-i-use-su-to-execute-the-rest-of-the-bash-script-as-that-user) solve your problem? – Gordon Davisson Nov 08 '22 at 07:22
  • Maybe this will help - [runuser](https://man7.org/linux/man-pages/man1/runuser.1.html) and send it to the background with _&_? – Monsieur Merso Nov 08 '22 at 09:12

0 Answers0