13

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?

5
  • 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 Commented Apr 7, 2016 at 12:30
  • 1
    @EricRenouf Yes, I'm root.
    – Getz
    Commented Apr 7, 2016 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
    Commented Apr 7, 2016 at 12:32
  • 1
    @AFH As root, su doesn't ask for a password too.
    – Getz
    Commented Apr 7, 2016 at 12:41
  • ... which means that as root there is little difference, apart from the PAM configuration.
    – AFH
    Commented Apr 7, 2016 at 15:36

2 Answers 2

16

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)

2

runuser is not 'su without PAM' (at least, not in 2023). From the 2.37.2 manpage:

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. The command runuser does not have to be installed with set-user-ID permissions. https://manpages.ubuntu.com/manpages/jammy/man1/runuser.1.html

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .