-1

I always want to run a script as user1, but the code flow always runs it as root. So, I want to check the current user inside the script. If it is root, I want to run the rest of the script as user1.

I want to do something similar to this. But only difference is I need to run the script as a particular user (say user1). So, when I find that the current user is not user1, I do not want to exit but want to run rest of the shell script as user1. How can I achieve this?

3
  • 1
    Check this: superuser.com/questions/468161/… Commented May 22, 2021 at 7:32
  • This sounds like a bad idea from a security perspective. Commented May 22, 2021 at 14:14
  • It shouldn't really matter who runs the script. If it needs to run as user1, it should be on the caller to ensure that happens. Commented May 22, 2021 at 14:17

1 Answer 1

2

Thanks @User123. But I was facing some issues with that solution as there are many functions and variables in the script. Not sure what the problem exactly is. But, this worked for me now:

 if [ $USER == <undesired user> ]; then
  echo Current user is $USER. Running the script as <desired user>
  su -c 'sh <script.sh>' <desired user>
 else
  echo Current user is $USER
  ...
  <rest of the script>
  ...
 fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.