Differences between su and su -

When you use Debian/Ubuntu for a long time, you tend to forget about su and gradually you both grow apart. I witnessed the same thing yesterday. I was working in a lab and my friend asked me, “Why’d you use su -. Why not a simple su!”. I replied, "Duh!" and then sat silently the rest of the time wondering why I couldn't remember a thing about the command which has been hard-coded in my brain all this time while my friend enjoyed the blackout.

So, I referred to our dear friend - manpages. And according to them, the “-” or “-l” or “--login” option provide us:

An environment similar to what the user would expect had the user logged in directly.

This statement refers to login shells. What’s that? Its the shell spawned when a user logs in. So, how's it different from a regular shell? They look same because in the end its always a prompt. But for both of them, different set of scripts/configuration files are executed before the prompt hits the terminal.

Lets take the example of bash. If you run a regular bash command, the files executed is ~/.bashrc which in turn may call /etc/bashrc. And when its a login shell(try “bash -l”), the execution order is /etc/profile, ~/.bash_profile which my call other files internally.

The key point is that different configuration in these files leads to different behaviours of the shell. One of the biggest differences is made by the initialization of PATH variable in ~/.bash_profile script(default behaviour). So, unless you open a login shell, you won’t get the expected PATH variable.

Here is a small demo:

Scenario 1

[shredder12]$ su
[root]# fdisk -l
fdisk: command not found
[root]# echo $PATH

Scenario 2

[shredder12]$ su -
[root]# fdisk -l
“works like a charm”
[root]# echo $PATH

As you can see the PATH environment variable was not set correctly. */sbin directories were not included in the first scenario. That's because it inherited the PATH variable of the previous user's shell i.e. shredder12. Hence, even on a root shell it didn’t feel like a root user.

1 Comment

antim grahan (not verified)
February 23rd, 2011 12:35 am
Nice Info. havent think of It before.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <p> <br>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Image links with 'rel="lightbox"' in the <a> tag will appear in a Lightbox when clicked on.

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.