Sudo – Purpose of Using `sudo -S` Explicitly

sudo

From manpage of sudo:

-S, –stdin

Write the prompt to the standard error and read the password from the
standard input instead of using the terminal device. The password must
be followed by a newline character.

What is the purpose of using sudo -S instead of just sudo?

  • Is it correct thatsudo by default read password from standard input?

  • What is the purpose of "Write the prompt to the standard error"? Does sudo by default write it to the standard output?

  • Do they both require that the password must be followed by a newline character?

For example, in https://stackoverflow.com/a/39553081/156458, sudo -S true still requires typing in password, so how does it solve the original question in that post? I found that link when I searched for solution to Shall I run a sudo-required script in some shell configuration file?

Thanks.


Update:

The reply by J.Taylor said

sudo does not read the password from stdin by default – it reads it from the terminal interface.

I was wondering how to understand it in terms of implementation.

Is it correct that when a program reads from standard input, it reads from file descriptor 0 to which the standard input is always binded?

Why can't I tell whether sudo uses standard input or terminal when usingsudo without -S?

How can a program (such as sudo -S) achieve to read from terminal instead of standard input?

Best Answer

sudo does not read the password from stdin by default - it reads it from the terminal interface. Using sudo -S allows you to pipe the password in from another command/file like this: printf "yourpassword\n" | sudo -S nano /etc/apt/sources.list

This could be used in a shell script to log in to sudo without being prompted for a password, but you need to be careful not to execute this kind of thing from the shell directly, because then your sudo password would be in the shell history.

Related Question