使用bash 4.1.2和4.3.48,以下脚本给出了预期的输出:
#!/bin/bash
returnSimple() {
local __resultvar=$1
printf -v "$__resultvar" '%s' "ERROR"
echo "Hello World"
}
returnSimple theResult
echo ${theResult}
echo Done.
Run Code Online (Sandbox Code Playgroud)
按预期输出:
$ ./returnSimple
Hello World
ERROR
Done.
Run Code Online (Sandbox Code Playgroud)
但是,当函数的stdout通过管道传递到另一个进程时,__resultvar
变量的赋值不再起作用:
#!/bin/bash
returnSimple() {
local __resultvar=$1
printf -v "$__resultvar" '%s' "ERROR"
echo "Hello World"
}
returnSimple theResult | cat
echo ${theResult}
echo Done.
Run Code Online (Sandbox Code Playgroud)
意外输出:
$ ./returnSimple
Hello World
Done.
Run Code Online (Sandbox Code Playgroud)
为什么printf -v
不在第二种情况下工作?应该printf -v
不写入值结果变量独立的函数的输出是否被管道输送到另一个进程?
请参阅以下man bash
部分Pipelines
:
管道中的每个命令都作为单独的进程执行(即,在子shell中).
这就是为什么当你写cmd | cat
,cmd
收到一个无法修改的变量的副本.
一个简单的演示:
$ test() ((a++))
$ echo $a
$ test
$ echo $a
1
$ test | cat
$ echo $a
1
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
375 次 |
最近记录: |