5.1. Running a root Login Shell
Problem
While logged in as a normal user, you need to run programs with root privileges as if root had logged in.
Solution
$ su -
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
See Also
su(1), env(1), environ(5). Your shell’s manpage explains environment variables.
Get Linux Security Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.