su - Linux


Overview

The su command, short for switch user, is used in Unix and Linux systems to switch the current user context to another user. It’s primarily used when administrators need to execute commands with privileges of another user, typically the root, without logging out and back in as that user. This command is crucial in system management, allowing controlled access to superuser privileges.

Syntax

The basic syntax for the su command is:

su [options] [username]

If no username is provided, su defaults to the root user. Here are variations in its usage:

  • Standard switch: su - username
  • Without a login shell: su username

Options/Flags

Here are the common options and flags for the su command:

  • , -l, –login: Starts a login shell with an environment similar to a real login:
    • Home directory is set to the target user’s home.
    • User and group ID are set to the target user.
    • Shell environment variables ($LOGNAME, $HOME, etc.) are set to those of the target user.
  • -c COMMAND, –command=COMMAND: Executes a single COMMAND as the specified user and then exits.
  • -s SHELL, –shell=SHELL: Runs the specified SHELL if it is allowed in /etc/shells.
  • -m, -p, –preserve-environment: Preserves the previous environment, which is the environment from which su is invoked.

Examples

  1. Switch to root user with a login shell:
    su -
    
  2. Execute a command as another user:
    su -c 'apt update' - username
    
  3. Switch to user without a login shell:
    su username
    
  4. Using a specific shell:
    su -s /bin/zsh username
    

Common Issues

  • Authentication failures: Ensure the correct password for the target user is entered. Repeated failures can be due to incorrect password or account restrictions.
  • Permission denied errors when running certain commands: Some commands may require root privileges. Use su - to switch to the root user with the appropriate environment.
  • Environment variable issues: Using su without - might not change all environment variables, causing unexpected behavior in scripts or commands.

Integration

The su command can be integrated with other commands or in scripts to automate tasks that require switching users. For example:

su - root -c 'sudo apt update && sudo apt upgrade'

This command updates system packages by switching to the root user, then executing the package manager commands.

  • sudo: Unlike su, sudo executes a single command as another user without switching to their environment completely.
  • whoami: Useful for checking the current user after a switch.

Visit the official GNU Core Utilities documentation for more detailed information on su and related commands.