问题
I know that sudo bash -c 'some_command' will run some_command with the same privileges as sudo.
I'm confused as to what's happening? Does it run some_command in bash as sudo (same as sudo bash) then switch back to my current user? Why am I not left in an instance of bash with sudo privileges like I would when I run sudo bash?
I tried running man bash and it describes the -c option (quoted below).
However, I am struggling to piece how the description relates to the behaviour I observed when running sudo bash -c 'some_command'
If the -c option is present, then commands are read from the first non-option argument command_string. If there are arguments after the command_string, they are assigned to the positional parameters, starting with $0.
回答1:
sudo switches users and then executes bash, passing it the other arguments. bash running as the new user runs the command in the argument after -c.
回答2:
Consider this snippet (pay attention to UID & PID/PPID columns.):
$ sudo ps -f
UID PID PPID C STIME TTY TIME CMD
root 8997 8715 0 11:57 pts/17 00:00:00 sudo ps -f
root 8998 8997 0 11:57 pts/17 00:00:00 ps -f
$ sudo bash -c 'ps -f'
UID PID PPID C STIME TTY TIME CMD
root 8909 8715 3 11:55 pts/17 00:00:00 sudo bash -c ps -f
root 8910 8909 0 11:55 pts/17 00:00:00 ps -f
$ sudo bash -c 'echo hi; ps -f'
hi
UID PID PPID C STIME TTY TIME CMD
root 8957 8715 0 11:56 pts/17 00:00:00 sudo bash -c echo hi; ps -f
root 8958 8957 0 11:56 pts/17 00:00:00 bash -c echo hi; ps -f
root 8959 8958 0 11:56 pts/17 00:00:00 ps -f
- In 1st case,
sudostartsps -fasrootuser. - In 2nd case,
sudostartsbashasrootuser with arguments-c 'ps -f'. It appears that as an optimization,bashis usingexecto startps -f. Hence, only 2 processes are seen. - In 3rd case,
sudostartsbashasrootuser with arguments-c 'echo hi; ps -f'. The command (argument to-c) is not a simple executable + args. They are 2 commands separated by;. So,bashcannot callexecdirectly. It uses the standardfork+execmechanism. So,bashis the parent of thepsprocess.
来源:https://stackoverflow.com/questions/37851390/what-happens-when-i-sudo-bash-c