Shell源文件输出管道vs重定向具有不同的效果。

时间:2018-01-11 23:18:52

标签: shell pipe io-redirection

我很难理解@JvmSuppressWildcards|运算符

之间的区别

我看过像:

这样的地方

https://www.gnu.org/software/bash/manual/html_node/Redirections.html

Pipe vs redirect into process

但是不能充分理解这些解释。

这是我的实际例子:

test-a.sh:

>

test-b.sh:

alias testa='echo "alias testa here"'

echo "testa echo"
echo "testa echo2"

test-pipes.sh:

alias testb='echo "alias testb here"'

echo "testa echo"
echo "testa echo2"

输出:

function indent() {
  input=$(cat)

  echo "$input" | perl -p -e 's/(.*)/  \1/'
}

source test-a.sh | indent
testa

source test-b.sh > >(indent)
testb

管道不允许在当前进程中设置别名,但重定向确实如此。

有人可以给出一个简单的解释吗?

1 个答案:

答案 0 :(得分:1)

来自bash man page

  

管道中的每个命令都作为一个单独的进程执行(即在子shell中)。

子进程所做的许多事情都与父进程隔离开来。其中包括:更改当前目录,设置shell变量,设置环境变量和别名

$ alias foo='echo bar' | :
$ foo
foo: command not found

$ foo=bar | :; echo $foo

$ export foo=bar | :; echo $foo

$ cd / | :; $ pwd
/home/jkugelman

注意没有任何更改生效。您可以使用显式子shell查看相同的内容:

$ (alias foo='echo bar')
$ foo
foo: command not found
$ (foo=bar); echo $foo

$ (export foo=bar); echo $foo

$ (cd /); pwd
/home/jkugelman
另一方面,

重定向不会创建子壳。它们只是改变命令输入和输出的位置。函数调用也是如此。函数在当前shell中执行,没有子shell,因此它们可以创建别名。