SU Command

Howto switch users using the su command

su command

Running the "su" command allows a user to temporarily become another user. When invoked "su" will run a command or shell as the user ID, Group ID and supplemental groups of that user.

Basic Syntax of su: su [OPTION] ... [USER [ARG]...]

If no user is passed to the "su" command, then the root user is assumed. The shell that is opened is of the type specified within the "/etc/passwd" file. (Mostly will be /bin/bash). When you execute the "su" command you will be asked to supply the password for the user you are trying to become. However, if you are running with root privileges (super user), then you will not be asked for a password. If you wish to pick up the same environment as the user you are passing, then you must use the "su -l" option. This sets the environment to a login environment.

Example of su with and without the "-l" parameter

Notice the difference in the PATH variable when we specify the "-l" or "-" option.

sles01:/home/john # id
uid=0(root) gid=0(root) groups=0(root),105(sfcb)
sles01:/home/john # echo $PATH

sles01:/home/john # su john
john@sles01:~> id
uid=1008(john) gid=100(users) groups=100(users),16(dialout),33(video),17000(dba)
john@sles01:~> echo $PATH
john@sles01:~> exit

sles01:/home/john # su -l john
john@sles01:~> echo $PATH

Running a command as another user and environment

If you pass the "-c" , then you can pass a command line to run as the specified user. If you are root the "root" user, you will be asked to confirm your password for the specified account.

sles01:/home/john # su - john -c "TestProgram"

The above would run the command or program "TestProgram" as the user "john". In the above example, you would not be prompted for a password as this command was issued by the "root" user.

su available options

  -, -l, --login               make the shell a login shell
  -c, --command=COMMAND        pass a single COMMAND to the shell with -c
  --session-command=COMMAND    pass a single COMMAND to the shell with -c
                               and do not create a new session
  -f, --fast                   pass -f to the shell (for csh or tcsh)
  -m, --preserve-environment   do not reset environment variables
  -p                           same as -m
  -s, --shell=SHELL            run SHELL if /etc/shells allows it
      --help     display this help and exit
      --version  output version information and exit