Diference between su and su –

Yeah, there’s a diference between su and su –. A while ago i stumbled upon this particularity when i didn’t know what difers between both. But it turns out to be really simple.

The “switch user” command

First things first. So what the “switch user” command does? Man pages, typically say:

su allows to run commands with substitute user and group ID.

man pages

Which means, you can temporarily, run commands on your session as if you were other user.

Usage example

[jrusso@centos ~]$ su linda
[linda@centos jrusso]$

[jrusso@centos ~]$ su – linda
[linda@centos ~]$

False friends

Technically, if you run the command with or without the hyphen (-), both appear to work either way the same way right? ehhhhhh! wrong!!! They look like it, but they are not.

Environment variables

Now here is the point about this article. Most admins, at least the ones i know, all use the following command when they want to change to root:

[jrusso@centos ~]$ sudo su –
[root@centos ~]$

I always used this method to run some scripts with root permissions, but one day, i forgot to put the “-“, and some things did not work anymore everytime i ran them in root. It was when i searched for it and discovered this little particularity…environment variables are not loaded the same way when you dont type hyphen (-). Man pages say:

-, -l, –login
Starts the shell as login shell with an environment similar to a real
login

man pages

That being said, when you simply run su, only some environment variables are changed, like HOME, SHELL, USER and LOGNAME. However, if you run with hyphen (-), the shell will load as a login one and all variables described in shell login files will be loaded. If you want know more about bash login files, check it out here: Bash Login Files Main Diferences.

Overall

Remember, just because the command apperantly works the same way (at naked eye) with or without the hyphen (-), doesn’t mean it wont have changes in the background. It’s Linux, every detail counts.

Leave a Reply

Your email address will not be published. Required fields are marked *