Bob_From_IT
Bob_From_IT

Reputation: 37

Script won't run with correct environmental variables when run with su

I've got a script that I wrote that calls another script but doesn't specify where that script is because it's location should already be in the user's PATH. By default the user starts in ksh and I've setup the .kshrc file to define all the various directories I need in the PATH variable. If I run it as the user then it runs fine, but if I try and run it in an su command then it fails. For example, this won't work

su - user1 -c "myscript.sh"

I was under the impression that by using the dash with the su command that it would load that users environment. Is that not correct? Is there a way around this other then specifying the full path to the other script I'm calling?

Upvotes: 1

Views: 996

Answers (3)

Kurtis Rader
Kurtis Rader

Reputation: 7469

I was under the impression that by using the dash with the su command that it would load that users environment. Is that not correct?

Not quite. It causes the shell to be a "login" shell. What that means is the shell command name is prefixed with a dash. If you type man ksh and scroll to the "Invocation" section you'll see that the rules for which "dot" files are read when the shell starts are arcane. Note that by default ~/.kshrc is only read for interactive shells. Since you are executing a script it won't be an interactive shell. You can force reading .kshrc by using the -E flag. But note that in general you should not set env vars like PATH in your .kshrc file.

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 247042

I assume you want to run the script with user1's login environment. Assuming user1's login shell is bash, you can do

su - user1 -lc myscrip.sh

which passes the -l option to bash: see Bash Startup Files for what that means.

Upvotes: 0

R4444
R4444

Reputation: 2114

You can do:

su - user1 -c "bash myscript.sh"

If it doesn't work:

su - user1 -c "bash /full-path-to-the-file-from-root/myscript.sh"

Upvotes: 0

Related Questions