Problem Statement
What is the difference between su and su - commands?
Explanation
Su (substitute user) switches to another user account, defaulting to root if no username specified. Plain su command switches user but maintains the current environment (PATH, variables, working directory). This can cause issues if the new user's environment differs significantly from the original user's environment.
Su - (or su -l) starts a login shell for the target user, fully switching to their environment including PATH, HOME, SHELL, USER variables, and changing to their home directory. This simulates a fresh login as that user. Su - is generally preferred because it provides a clean, expected environment for the target user.
Examples: su switches to root keeping current environment, su - root switches to root with root's full environment, su - john switches to john with john's environment. Su -c 'command' user runs a single command as user without starting interactive shell. Sudo is generally preferred over su for administrative tasks due to better auditing and the principle of least privilege.
Understanding the difference prevents environment-related issues when switching users, especially when running commands that depend on specific environment variables or paths. For automation and scripts, explicitly specify environment requirements rather than relying on inherited environment.
