2

I'm currently working on a script that logs into another user account using

su username -c "comand1; comand2" 

There's no sudo command in the shell.

However the environment variables do not change.

For example, the work directories are different with different users. So when the user is switched in the script, I expect that the $HOME variable should contain different work directories.

Does anyone know how to solve this problem?

3 Answers 3

3

You are probably looking for the -l (or just -) option to make it a login shell. See the manual for su(1).

Sign up to request clarification or add additional context in comments.

2 Comments

it sort of worked but not what i desired. I called another script within the first script and work directory is correct in the second script. But the environment variables still no change in the first script
You should really specify what OS and what shell.
0

One hack-ish kind of way would be put all env variables of the second user in a file (like .bashrc) and source it first in the list of the commands:

su username -c "source file_name; comand1; comand2" 

Comments

0

There are two issues:

First: If you user " to delimit the argument for -c then everything in this argument is expanded by the calling shell and not by the executed shell. You can use ' instead of " to prevent this.

Second: By default su does not perform the same steps as during a real user login. Use the -l or - options. This may be required in your case or not - just try it.

Together:

> echo $HOME
/root
> su -c "echo $HOME" user -l
/root
> su -c 'echo $HOME' user -l
/home/user
> su -c 'echo $HOME' user
/home/user

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.