2016-06-30 86 views
2

背景

[ 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一个新的外壳命令替换过程中产生了。此时我更改了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环境变量的修改,这有助于壳找到二进制文件。然而,当我和命令替换一起阅读时,我感到困惑。

如果$(..)子外壳被衍生,然后环境变量PATH应完好无损并应指向二进制(cut在这种情况下)等的bash不应抱怨它不能找到cut二进制。

问题

怎么了PATH的修改在这里影响命令替换?

+1

我认为你对子外壳中'PATH' *的变化与*子外壳继承的'PATH' *的变化相混淆。 – chepner

+0

@chepner:其实我忽略了PATH是一个环境变量的事实,并且它不需要导出以使更改生效。 – sjsam

+2

啊,好的。请记住,“导出”变量实际上意味着标记其名称,以便与该名称关联的*值*被添加到任何子进程的环境中。环境变量是一个从环境初始化的变量,会自动导出。 – chepner

回答

4

考虑下面的例子:

$ 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相同。)

+0

完美!你能否引用'''''''''''从文档中继承'和父shell一样的环境''。 – sjsam

+0

^^我找不到': - /'。再试... – anishsane

+0

没有probs ..把你的时间。 – sjsam