Understand Linux Su Command Function With Example

September 26, 2012 | By
| Reply More

Su Command

Linux is a multiuser Operating System kernel. Multiple users can login to a Linux system simultaneously. You can switch between different users on the command line itself with su command. The su command can switch between users. This command changes the user credentials to those of a specified user or root (by default). This article discusses su command and difference between su and su - commands.

The su command

The su command, as stated above will change the user's credentials to some other usesr's. The following command describes the basic usage of su command:

[raghu@redhat-server ~]$ su jack
[jack@redhat-server raghu]$ id
uid=501(jack) gid=501(jack) groups=501(jack),504(javaproject) context=root:system_r:unconfined_t:SystemLow-SystemHigh

The id command outputs the information about the current user. In above output, you can see the changed user. When no arguments are given to su command, it changes to root user by default.

[jack@redhat-server raghu]$ su
[root@redhat-server raghu]# id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel) context=root:system_r:unconfined_t:SystemLow-SystemHigh

Simulating login with su -

With su --login or su -l or just su - command, you can switch user as if it were a login from a terminal.

[raghu@redhat-server ~]$ su - jack
[jack@redhat-server ~]$ id
uid=501(jack) gid=501(jack) groups=501(jack),504(javaproject) context=root:system_r:unconfined_t:SystemLow-SystemHigh

su vs su-

The difference between su and su - is that some environment variables such as PATH variable do not change values with just su (i.e. if -l option or - is ommitted). Some commands may not run if PATH is not properly set. For example consider the following scenario:

[jack@redhat-server ~]$ su root
[root@redhat-server jack]# fdisk -l
bash: fdisk: command not found
[root@redhat-server jack]# echo $PATH

You can see that sbin directories are not included in the root user's PATH. So it does not run the fdisk command. Now we try to login with su - command:

[jack@redhat-server ~]$ su -
[root@redhat-server ~]# fdisk -l

Disk /dev/sda: 8589 MB, 8589934592 bytes
255 heads, 63 sectors/track, 1044 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sda1 * 1 13 104391 83 Linux
/dev/sda2 14 1044 8281507+ 8e Linux LVM
[root@redhat-server ~]# echo $PATH

Another difference between these two commands is of the login scripts. First let's discuss some login scripts:

When a user logs into a system, following 4 files are executed if the user's credentials are legitimate:


When you login with su - command, all of these scripts are executed. But with su, only bashrc scripts are executed, i.e. /etc/bashrc and ~./bashrc scripts are executed.


Tagged With :

Free Linux Ebook to Download

Leave a Reply

All comments are subject to moderation.