I'm running a bash script from a root perspective which then starts a program in the script

su -c "sh /home/user2/script.sh" -m user2

The problem is that the program started by this script, while executed as user2, is still trying to create files in /root/.config/, which of course fails as it's not permitted by user2.

Am I doing anything wrong? Is is there another better way to actually change user in the script, enter the user's password then start the program?

  • 2
    The -m parameter preserves the calling shell's environment, so $HOME will remain set to /root if called from a root shell. Why have you used it? And why are you calling the Bourne shell to run a bash script? – AFH Sep 15 '17 at 23:35
  • Oh wow thanks.. I thought the "m" parameter was too specify the user, totally misunderstood as I took that command from another stash overflow question. – NaturalBornCamper Sep 16 '17 at 8:44
  • About the Bourne shell.. that's all I ever used, didn't know I shouldn't always use it – NaturalBornCamper Sep 16 '17 at 8:45
  • Your question is tagged with [bash] and it begins with "I'm running a bash script ...". It is unusual these days not to use Bash, as that is the default shell with most Linux distributions. If your script begins with #!/bin/bash or #!/bin/sh, that will determine which shell is used, regardless of the shell it was launched from. In passing, it is common for sh and bash to be the same program, with switches to define which syntax to use. I'll answer your question, so that others can see that there is an answer, – AFH Sep 16 '17 at 8:59
up vote 2 down vote accepted

If you use the -m parameter with su, it will pass your current environment to the command or shell being executed. In particular, the $HOME variable will be set to its value in the calling shell and not determined by the user invoked.

So, if you're logged in as root, $HOME will be /root and remain so when executing script.sh under su -m. Unless there are other parts of the environment that you want to preserve, you can simply omit the -m from the su call.

  • Wow thanks a lot! +1 for the full explanations, hope someone can use that. I've been using Linux for a while but as an amateur so I don't know about the details like this, very helpful! – NaturalBornCamper Sep 16 '17 at 13:29

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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