I need to run some command lines as particular user in a shell script.

I've found (at least) two way:

su user -c 'command'

runuser -l user -c 'command'

Is there a significant difference between this two commands?

  • 1
    Are you root when you're running them? If not runuser might not be able to do what you want. You have to run it as a user who has the privs to set the UID to the target user, while su will handle that for you – Eric Renouf Apr 7 '16 at 12:30
  • 1
    @EricRenouf Yes, I'm root. – Getz Apr 7 '16 at 12:32
  • From man runuser: "The difference between the commands runuser and su is that runuser does not ask for a password (because it may be executed by the root user only) and it uses a different PAM configuration." – AFH Apr 7 '16 at 12:32
  • 1
    @AFH As root, su doesn't ask for a password too. – Getz Apr 7 '16 at 12:41
  • ... which means that as root there is little difference, apart from the PAM configuration. – AFH Apr 7 '16 at 15:36

As already written in question comments, runuser is basically a su that doesn't use the PAM stack.

To provide a little more detail, as per blog post of Dan Walsh - one of runuser authors - it seems that runuser is actually compiled from su sources except with the PAM stack excluded from compilation. The difference is that using runuser instead of su can prevent some SELinux errors. That post also says this:

Whenever an service is running as root and wants to change UID using the shell it should use runuser.

When you are logged in to a shell as a user and want to become root, you should use su. (Or better yet sudo)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.