15

Is there any difference between using sudo and using su -c? There are situations where one should be used but not the other?

I was previously using Ubuntu where sudo appears to be ubiquitous but now I'm giving Fedora 15 a try and the idiom su -c appears frequently when I'm trying to learn how to do a few things, although I still see sudo being used now and then.

2

2 Answers 2

19

The difference between sudo and su is how they perform authentication:

  • su prompts for the target user's password.
  • sudo checks whether the source user is authorized to run the command (the authorization is specified in /etc/sudoers). Depending on the configuration, it might prompt for the source user's password, both to mitigate the risk of an unattended console and to alert the user that privilege escalation is going on.

Once authorized, the effect is the same: run a command as root (or, if specified on the command line, as some other user).

There are further minor differences: they don't take the same options, and they don't set the environment for the command they run in exactly the same way. The meaning of “command” is slightly different: for su -c, it's a string that's executed by the target user's shell, whereas for sudo with no options, it's a program to run with arguments. But for common usage, they're the same.

2
  • The OP specifically asked about su -c and not just su. It's ok to explain the base command, but you should've included an explanation for the -c argument. You just explained what was optional.
    – Chazy Chaz
    Jan 18, 2022 at 13:53
  • @ChazyChaz An explanation of what? sudo and su -c both run a command in a different user account, root by default. I don't know what else to say. Were you expecting a detailed explanation of how they set up the environment differently (which would be pretty hard because that's very dependent on the system configuration)? Ok, I suppose it would be useful to mention that su -c uses the target user's shell whereas plain sudo doesn't. Jan 18, 2022 at 15:34
5

They are different in semantics.

Using su means you don't want the invoked process to be aware of the fact that you are not the real target user. The man page recommends always taking option su --login.

Using sudo means the opposite. sudo even sets a new environment variable SUDO_UID to tell the process who you really are.

BTW, su is adapted to ancient unix display manager or shell profile, which set only a few number of environment variables (HOME, PATH, etc) before invoking the interactive shell. And su will reset those variables.

However modern init systems set much more environment variables. e.g. Linux PAM sets XDG_RUNTIME_DIR, which will not be reset by su. Hence, su --login cannot emulate a real login. See https://github.com/systemd/systemd/issues/7451#issuecomment-346787237

You must log in to answer this question.

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