Running a command as another user

 · 1 min · torgeir

Terminal Su Linux
  • Rescheduled from “[2023-04-02 Sun]” on [2023-05-27 Sat 09:24]

The su program lets you run a command and subsitute the user and group id.

With -c you can run a command as another user.

[root@box ~] su -c "whoami" another-user

You can add arguments by tacking them on at the end. Make sure to use single quotes, ', if you plan to refer arguments such as $1, or else they will be expanded before the su command is run.

[root@box ~] su -s /bin/zsh -c 'echo script $0, one $1, two $2' another-user name 1 2
script name, one 1, two 2

You can use -p to preserve the environment for the current user.

[root@box ~] su -c "env | grep HOME" another-user
[root@box ~] su -p -c "env | grep HOME" another-user

With -l it will start the shell as a login shell, clearing env-vars except for TERM, initializing HOME, SHELL, USER, LOGNAME and PATH. It will also move to the user’s home directory.

[root@box ~] su -c "pwd" another-user

Like this

[root@box ~] su -l -c "pwd" another-user

The shell can be specified with -s.

[root@box ~] su -s /bin/zsh -c 'echo $SHELL' another-user