3

User x run a script. Now I want to change the user in the script to User y.

#!/bin/sh
whoami
echo password | su y
whoami

But I get this:

x
su: must be run from a terminal
x

Thanks for your help.

3 Answers 3

14

This is working for me inside a bash script:

whoami;
sudo su $user << BASH
  whoami;
BASH
Sign up to request clarification or add additional context in comments.

1 Comment

Only works where sudo is available. Debian has no sudo command.
5

Su cannot be ran in a Bash script. You can use sudo -u <user> <command> && however.

1 Comment

Not entirely true. It is possible to run su from a script as long as you give it a terminal. For example:ssh -t user@localhost "su -c whoami"
-2

you can do:

su - $USER -l -m -c $CMD

-l provide an environment similar to the login env -m preserves the current environment -c runs the command

e.g. I use this to run nohup commands also

su - $USER -l -m -c "nohup $RUN_CMD > "$LOG" 2>&1 >> /dev/null&"

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.