Bash Scripting – su Options for Running Commands as Another User

bashscriptingsusudo

I was wondering how to run a command as another user from a script.

I have the script's owner set as root. I also have the following command being run within the script to run the command as the hudson user:

su -c command hudson

Is this the correct syntax?

Best Answer

Yes. Here's the --help:

$ su --help
Usage: su [options] [LOGIN]

Options:
  -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

And some testing (I used sudo as I don't know the password for the nobody account)

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

When your command takes arguments you need to quote it. If you don't, strange things will occur. Here I am —as root— trying to create a directory in /home/oli (as oli) without quoting the full command:

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

It's only read mkdir as the value for the -c flag and it's trying to use /home/oli/java as the username. If we quote it, it just works:

# 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: -
Related Question