Saturday, January 30, 2010

What is the difference between "su -" and "su" ?

The main difference between su - and su is that the former makes the shell a login shell. This is very important especially if the user is going to su from a regular user account to a root (superuser) account. Normal users do not usually have /sbin/ and /usr/sbin/ in their search path. Therefore if a normal user wants to execute the command ifconfig, for example, after doing su, he usually gets the error message:

bash: ifconfig: command not found

With su -, on the other hand, root's .bashrc and .bash_profile and other special environment settings get sourced and this puts the sbin directories into the search path. Below is a sample session:

[testuser@localhost ~]$ su
Password:
[root@localhost testuser]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/testuser/bin
[root@localhost testuser]# ifconfig
bash: ifconfig: command not found
[root@localhost testuser]# exit
exit
[testuser@localhost ~]$ su -
Password:
[root@localhost ~]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin
[root@localhost ~]# ifconfig
eth0 Link encap:Ethernet HWaddr 00:A0:CC:39:75:41
inet addr:192.168.44.146 Bcast:172.16.45.255 Mask:255.255.254.0
inet6 addr: fe80::2a0:ccff:fe39:7541/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:21619559 errors:1 dropped:0 overruns:0 frame:87
TX packets:21190195 errors:4 dropped:0 overruns:4 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1509569968 (1.4 GiB) TX bytes:2280347397 (2.1 GiB)
Interrupt:177 Base address:0x6800

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:6159 errors:0 dropped:0 overruns:0 frame:0
TX packets:6159 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:3784618 (3.6 MiB) TX bytes:3784618 (3.6 MiB)

3 comments:

prashant thumbar said...

great...sir

Anonymous said...

I hsve a question? I am using CentOS and I have the following problem:

When I use su - to change user I get the following error:
-bash: [root: command not found

the same is happening when I use putty to login into the system as root.

Do you know why this is happening?

Unknown said...

su gives you root permissions but it does not change the PATH variable and current working directory. so you can't execute files in /usr/sbin folder.

su - changes the PATH too... and root's home becomes your current working directory. you become proper root and can execute all commands.

$ su
$ echo $PATH
$ pwd

note down the output of path and pwd. now execute su - check the difference