Linux commands
Browse topics

Running commands as another user with sudo

Version
unversioned
Review
Draft

Summary#

sudo runs one command as another user, root by default, if the system policy allows it.

Syntax#

sh
sudo apt update
sudo -u postgres psql
sudo -l
sudo -i
echo 'net.ipv4.ip_forward=1' | sudo tee /etc/sysctl.d/90-forward.conf
sudo visudo

-u selects the user, -l lists what you may run and -i starts a login shell. visudo edits the policy and checks its syntax before saving.

Example#

Run this only on a disposable system where your account has passwordless sudo. It writes one file inside its own temporary directory.

sh
(
  set -eu
  dir=$(mktemp -d)
  trap 'rm -rf -- "$dir"' EXIT

  sudo -n id -u
  sudo -n -u nobody id -un
  echo 'set by root' | sudo -n tee "$dir/root.txt" >/dev/null
  stat -c %U "$dir/root.txt"
)

Expected output#

Text
0
nobody
root

Common mistakes#

In sudo echo text > /etc/file, your shell opens the file before sudo starts, so write with sudo tee. user is not in the sudoers file means the policy grants that account nothing; an administrator must add it, usually through a group such as sudo or wheel. With -n, sudo fails and says that a password is required instead of prompting. Edit the policy only with visudo, since a syntax error can lock out every sudo user. Prefer a single command over a root shell.

Version applicability#

This entry describes sudo 1.9. Ubuntu can also provide sudo-rs, which supports a smaller set of features and words some messages differently.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0