Skip to content

su Command Cheat Sheet

su (substitute user or switch user) allows you to run commands with the privileges of another user account.


Synopsis

su [options] [username]

Basic Usage

Switch to Root

If no username is given, root is assumed. You must know the target user's password.

su

Switch to Another User

su database_admin

Login Shell (-)

Critical Concept:

  • su (without dash): Keeps your current environment variables (HOME, SHELL, USER, PATH). This can cause permission issues.
  • su - (with dash): Starts a fresh login shell. Resets environment variables to the target user's defaults (reads .bash_profile etc.).

Correct Way to Become Root

su -

Correct Way to Become User

su - postgres

Execute Command (-c)

Run a single command as another user and return.

su -c "ls -la /root" root
su - postgres -c "psql -l"

Specify Shell (-s)

If the target user has /sbin/nologin as their shell (common for service accounts like www-data), you can't switch to them normally. Use -s to force a shell.

sudo su -s /bin/bash www-data

su vs sudo

Feature su sudo
Password Target user's password Your own password
Privileges Full shell access Granular command control
Audit Hard to track specific commands Logs every command run
Usage Creating a session Running a command

Notes

  • Auth: su asks for the target user's password.
  • Sudo: sudo su asks for your password (if you are in sudoers), then switches to root.