命令行中如何解释括号?

命令行中如何解释括号?

在阅读如何设置时grub,我发现一篇文章声称我需要使用以下两种语法之一,

echo \(hd0,0\) >> /boot/grub/grub.conf

或者

echo '(hd0,0)' >> /boot/grub/grub.conf

因为在命令行中,括号以特殊方式解释。括号有什么特别之处?它们是如何解释的?

答案1

括号表示 bash 中的子 shell。引用该man bash页面:

(list)    list  is  executed  in  a  subshell  environment (see COMMAND
          EXECUTION ENVIRONMENT below).  Variable assignments and builtin 
          commands that affect the shell's environment do not remain in 
          effect after the command completes.  The return status is the
          exit status of list.

其中 alist只是一个正常的命令序列。

这实际上是相当便携的,并且不特定于只是bash。这POSIX Shell 命令语言规范语法描述如下(compound-list)

执行复合列表在子 shell 环境中;看Shell执行环境。影响环境的变量分配和内置命令在列表结束后不应继续有效。

答案2

嵌入之间的命令列表括号作为子 shell 运行。

子 shell 中的变量在子 shell 中的代码块之外不可见。父进程和启动子 shell 的 shell 无法访问它们。实际上,这些是局部变量。

Linuxtopia - 第 20 章. 子 shell

相关内容