Recipe 5.1 Running a root Login Shell

5.1.1 Problem

While logged in as a normal user, you need to run programs with root privileges as if root had logged in.

5.1.2 Solution

$ su -

5.1.3 Discussion

This recipe might seem trivial, but some Linux users don't realize that su alone does not create a full root environment. Rather, it runs a root shell but leaves the original user's environment largely intact. Important environment variables such as USER, MAIL, and PWD can remain unchanged.

su - (or equivalently, su -l or su ?login) runs a login shell, clearing the original user's environment and running all the startup scripts in ~root that would be run on login (e.g., .bash_profile).

Look what changes in your environment when you run su:

$ env > /tmp/env.user
$ su
# env > /tmp/env.rootshell
# diff  /tmp/env.user /tmp/env.rootshell
# exit

Now compare the environment of a root shell and a root login shell:

$ su -
# env > /tmp/env.rootlogin
# diff /tmp/env.rootshell /tmp/env.rootlogin
# exit

Or do a quick three-way diff:

$ diff3 /tmp/env.user /tmp/env.rootshell /tmp/env.rootlogin

5.1.4 See Also

su(1), env(1), environ(5). Your shell's manpage explains environment variables.



    Chapter 9. Testing and Monitoring