根据我的阅读,将命令放在括号中应该在子shell 中运行它,类似于运行脚本。如果这是真的,如果 x 未导出,它如何查看变量 x?
x=1
Run Code Online (Sandbox Code Playgroud)
(echo $x)
在命令行上运行结果为 1
echo $x
正如预期的那样,在脚本中运行不会产生任何结果
考虑以下(含sh
为/bin/dash
):
$ strace -e trace=process sh -c 'grep "^Pid:" /proc/self/status /proc/$$/status'
execve("/bin/sh", ["sh", "-c", "grep \"^Pid:\" /proc/self/status /"...], [/* 47 vars */]) = 0
arch_prctl(ARCH_SET_FS, 0x7fcc8b661540) = 0
clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fcc8b661810) = 24865
wait4(-1, /proc/self/status:Pid: 24865
/proc/24864/status:Pid: 24864
[{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 24865
--- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=24865, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---
exit_group(0) = ?
+++ exited with 0 +++
Run Code Online (Sandbox Code Playgroud)
没有什么不寻常的,从主 shell 进程中grep
替换了一个分叉进程(这里是通过 完成的clone()
)。到现在为止还挺好。
现在使用 bash 4.4: …
我试图理解为什么某些 shell 在使用sudo调用时似乎会受到特殊处理调用时似乎会受到特殊处理。例如,似乎有两种可能的行为:
\n“隐式”组(pstree是sudo的直接子级,中间没有 shell):
\n$ sudo pstree -s $$\nsystemd\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80login\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80bash\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80sudo\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80pstree\n$ sudo bash -c \'pstree -s $$\'\nsystemd\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80login\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80bash\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80sudo\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80pstree\n$ sudo zsh -c \'pstree -s $$\'\nsystemd\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80login\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80bash\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80sudo\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80pstree\n$ sudo dash -c \'pstree -s $$\'\nsystemd\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80login\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80bash\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80sudo\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80pstree\n
Run Code Online (Sandbox Code Playgroud)\n“显式”组(shell 是sudo的直接子级)的直接子级):
\n$ sudo ksh -c \'pstree -s $$\'\nsystemd\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80login\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80bash\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80sudo\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80ksh\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80pstree\n$ sudo tcsh -c \'pstree -s $$\'\nsystemd\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80login\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80bash\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80sudo\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80tcsh\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80pstree\n$ sudo fish -c \'pstree -s $fish_pid\'\nsystemd\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80login\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80bash\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80sudo\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80fish\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80pstree\n
Run Code Online (Sandbox Code Playgroud)\n显然sudo和一些 shell 之间似乎发生了某种集成,但我找不到任何相关文档。我还 grep 了sudo和bash的源代码,但也找不到任何线索。
这个另一个问题似乎相关:Why (...) does not …