Linux Su Command Tutorial With Examples
su short for substitute super user command using to change currently logged user. This makes things practical because the user change made without login. Su command can be used to get root privileges too. Su and sudo commands have different ways to act for similar aims.
su [options] [commands] [-] [username]
Man page of the command can be seen like below.
$ man su
To get fast and simple help the
-h parameter can be used like below.
$ su -h
This commands main usage area is changing current user and open new shell for the specified new user. While changing user current environment variables will not change and stay as old users environment variable. In this example we will change to the user
$ su root
Change User With Environment Variables
While changing user environment variables can be get with the
- parameter. If this parameter is not specified previous user’s environment variables will be used. We can see that after user is changed the working directory is also changed as root’s home.
$ su - root
Run Command As Different User
Some commands may be needed to run as different user. Every time changing user to run a command is not feasible. Commands can be run as specified user with the
-c parameter like below. In this example simple
ls command will be run as root user.
$ su -c ls root
While changing to different user or running command as different user shell may become important. Default existing shell can be changed with the
-s parameter. In the following example we will use primitive
sh shell for the root user.
$ su -s /bin/sh - root