带引号的 sudo 命令行为

sudo command behaviour with quotes

我需要你的帮助来理解 sudo 的这种行为。

sudo -s -- 'ls -l' 此命令有效,但 sudo 'ls -l' 抛出错误提示 sudo: ls -l: command not found 我意识到它将引号内的整个字符串视为单个命令(包括空格)但我不明白的是它如何与 -s 标志一起正常工作但在 -s 时失败不存在。

来自sudo man page

-s [command]

The -s (shell) option runs the shell specified by the SHELL environment variable if it is set or the shell as specified in the password database. If a command is specified, it is passed to the shell for execution via the shell's -c option. If no command is specified, an interactive shell is executed.

它的行为就像它那样,因为生成了一个新的 shell,它像 shells 那样分解了你的“引用命令”中的单词。

没有-s,第一个参数是要执行的命令的名称。对于 -s,第一个参数是传递给任何 shell($SHELL 或您的系统 shell)的 -c 选项的字符串,用于执行该参数.

即假设$SHELLsh,以下等价:

sudo -s -- 'ls -l'
sudo -- sh -c 'ls -l'