命令替换和$ PATH变量

时间:2016-06-30 04:38:28

标签: bash path command-substitution

背景

[ article ]说:

  

命令替换扩展为命令的输出。这些   命令在子shell ..

中执行

但是bash手册在其命令替换部分中没有说明subshell

我的测试

$ ps
  PID TTY          TIME CMD
26483 pts/25   00:00:00 bash
26866 pts/25   00:00:00 ps
$ hpid="$(ps | grep bash)"
$ echo "$hpid"
26483 pts/25   00:00:00 bash
26899 pts/25   00:00:00 bash

显示在命令替换期间生成了带有pid 26899的新shell。此时我更改了PATH环境变量。

$ PATH="/some/rogue/path"

做了以下的事情:

VAR="$(echo "Do|Die" | cut -d"|" -f 2)"

并得到以下错误:

Command 'cut' is available in '/usr/bin/cut'
The command could not be located because '/usr/bin' is not included in the PATH environment variable.
cut: command not found

我理解错误是由于修改了PATH环境变量,这有助于shell找到二进制文件。但是当我和命令替换一起阅读时,我很困惑。

如果通过$(..)生成一个子shell,那么PATH环境变量应该是完整的并且应该指向二进制文件(在这种情况下为cut),因此bash不应该抱怨它无法找到{ {1}}二进制。

问题

cut的修改如何影响命令替换?

1 个答案:

答案 0 :(得分:5)

请考虑以下示例:

$ export PS1='\$\$=$$ \$ '
$$=30862 $ a=123 # Note: No export a here.
$$=30862 $ echo $a
123
$$=30862 $ bash
$$=31133 $ echo $a # Subshell explicitly created does not have it.

$$=31133 $ exit
$$=30862 $ echo $(eval 'echo $a') # This subshell however does inherit it. The single quote ensures that this is not evaluated by parent shell.
123                               # echo $(echo $a) would probably cause $a to be evaluated by parent shell.
$$=30862 $

简而言之,$(...)生成的子shell继承了与父shell相同的环境,即使未导出变量也是如此。 (偶数$$与父shell相同。)