Mastering sudo: 4 Essential Commands for Root Access and User Switching
This guide explains four key sudo commands—sudo su -, sudo -i, sudo -s, and sudo "command"—detailing how each switches to the root environment, loads configuration files, and handles environment variables on Linux systems.
Introduction
When using Linux, switching privileges is commonly done with sudo or su root . Beyond these basic usages, sudo offers several advanced operations that many users overlook. This article walks through the most useful sudo commands.
1. sudo su -
This command logs in to a new root shell using the current user's password. It reloads system configuration files such as /etc/profile and /etc/bashrc , and also reloads the root user's $SHELL configuration (e.g., /root/.bashrc for Bash or /root/.zshrc for Zsh), providing a full root environment.
<code>$ sudo su -
# env | grep -E '(HOME|SHELL|USER|LOGNAME|^PATH|PWD|TEST_ETC|TEST_ZSH|TEST_PRO|TEST_BASH|TEST_HOME|SUDO)'
</code>2. sudo -i
This command behaves similarly to sudo su - , giving you a root environment while preserving some information about the invoking user.
<code>$ sudo -i
# env | grep -E '(HOME|SHELL|USER|LOGNAME|^PATH|PWD|TEST_ETC|TEST_ZSH|TEST_PRO|TEST_BASH|TEST_HOME|SUDO)'
</code>3. sudo -s
This starts a non‑login root shell using the current user's $SHELL . It does not load /etc/profile or other system-wide files, so variables defined there (e.g., TEST_ETC ) are absent, but it does load the root user's shell configuration (e.g., /root/.zshrc if $SHELL is Zsh). The working directory remains unchanged.
<code>$ sudo -s
# env | grep -E '(HOME|SHELL|USER|LOGNAME|^PATH|PWD|TEST_ETC|TEST_ZSH|TEST_PRO|TEST_BASH|TEST_HOME|SUDO)' --color
</code>4. sudo "command"
Prefix any command with sudo to execute it with root privileges, e.g., sudo git --version . When run, sudo resets the environment to a secure set of variables and does not load the user's shell configuration, so custom variables like TEST_ETC or TEST_PRO are missing. The secure path is defined in /etc/sudoers under the secure_path setting.
<code>$ sudo env | grep -E '(HOME|SHELL|USER|LOGNAME|^PATH|PWD|TEST_ETC|TEST_ZSH|TEST_PRO|TEST_BASH|TEST_HOME|SUDO)' --color
</code>Note that sudo echo $PATH and sudo env | grep PATH may show different values because the former expands $PATH before sudo runs.
The sudo capabilities, especially those defined in /etc/sudoers , are powerful and worth further exploration.
360 Zhihui Cloud Developer
360 Zhihui Cloud is an enterprise open service platform that aims to "aggregate data value and empower an intelligent future," leveraging 360's extensive product and technology resources to deliver platform services to customers.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.