Running a Command as a Different User: Alternative Approaches

The primary purpose of “switching users” is to switch between different users, while the purpose of “executing commands as other users” is to run commands on behalf of another user. For instance, consider the following scenario:
Question: I have two users, userA and userB. userB needs to execute certain commands as userA. To configure this, I have made the following settings in the system:
When I ran the command as userB, it prompted me for userB’s password. After entering the password, the command did not provide the expected fdisk output.


I was contemplating the method of executing a command as a different user within a script.

script’s owner
is set as root. Additionally, the script includes the command to run as the hudson user:

su -c command hudson

Is this the correct syntax?

Solution 1:

Certainly, presenting the requested information, here is the



$ su --help
Usage: su [options] [LOGIN]
  -c, --command COMMAND         pass COMMAND to the invoked shell
  -h, --help                    display this help message and exit
  -, -l, --login                make the shell a login shell
  -m, -p,
  --preserve-environment        do not reset environment variables, and
                                keep the same shell
  -s, --shell SHELL             use SHELL instead of the default in passwd

I conducted some testing by utilizing


since the password for the


account is unknown to me.

$ sudo su -c whoami nobody
[sudo] password for oli: 

When providing arguments to your command, it is necessary to enclose them in quotation marks. Failure to do so can result in unexpected outcomes. In this example, I am attempting to create a directory in /home/oli (as oli) while omitting the use of quotation marks for the entire command.

# su -c mkdir /home/oli/java oli
No passwd entry for user '/home/oli/java'

The value for the flag,


, is only read and it attempts to use


as the username. By quoting it, the issue is resolved and it functions properly.

# su -c "mkdir /home/oli/java" oli
# stat /home/oli/java
  File: ‘/home/oli/java’
  Size: 4096        Blocks: 8          IO Block: 4096   directory
Device: 811h/2065d  Inode: 5817025     Links: 2
Access: (0775/drwxrwxr-x)  Uid: ( 1000/     oli)   Gid: ( 1000/     oli)
Access: 2016-02-16 10:49:15.467375905 +0000
Modify: 2016-02-16 10:49:15.467375905 +0000
Change: 2016-02-16 10:49:15.467375905 +0000
 Birth: -

Solution 2:

Please note that setting the script’s owner as root does not have any effect. Even if the setuid bit is set, it still does not work.

If you are running the script as root, you can use


. While


is mainly for
switching users


is intended for
executing commands
as other users. To execute the command as a specific user, utilize the



sudo -u hudson command

Frequently Asked Questions