bash source 命令不适用于管道

Mat*_*tty 0 bash pipe

有 3 个文件(abc),均具有777权限:

$ ls
a  b  c
Run Code Online (Sandbox Code Playgroud)

上述文件有以下内容:

$ cat a
#!/bin/bash
export A=aaa
$ cat b
#!/bin/bash
source ./a
echo $A
$ cat c
#!/bin/bash
source ./a | >> log
echo $A
Run Code Online (Sandbox Code Playgroud)

b和之间的唯一区别c| >> log

$ diff b c
2c2
< source ./a
---
> source ./a | >> log
Run Code Online (Sandbox Code Playgroud)

执行时b会输出预期的结果aaa

$ ./b
aaa
Run Code Online (Sandbox Code Playgroud)

执行时c,对我来说,它输出一个意外的空白行而不是预期的aaa,并且log脚本c创建的文件是空的:

$ ./c

$ cat log
$
Run Code Online (Sandbox Code Playgroud)

显然,有些东西source|还没有学到。

有人可以告诉我为什么c不输出aaa吗?

Cha*_*ffy 6

使用进程替换而不是管道:

source ./a > >(tee -a log)
Run Code Online (Sandbox Code Playgroud)

这样您的source命令就会在原始 shell 中运行。

或者,完全停止创建管道:

source ./a >>log
Run Code Online (Sandbox Code Playgroud)