Bash - 管道变量和文件
问题描述:
在下面的简化示例中,“anything”正确地从$ S“变量回显到”S.gz“文件中,但变量从管道流中丢失:Bash - 管道变量和文件
echo 'anything' | tee >(read S | gzip >S.gz)
zcat S.gz
echo '$S='"$S"
呼应:
anything
$S=
期望的输出是:
anything
$S=anything
的另一种方法,同样不幸欧tput的:
echo 'anything' | tee >(read S) | gzip >S.gz
zcat S.gz
echo '$S='"$S"
呼应:
anything
$S=
任何想法?
答
read
必须在当前shell中执行;你需要反转你的管道。
read S < <(echo anything | tee >(gzip - > S.gz))
,或者在bash
4.2或更高版本,使用lastpipe
选项。 (请注意,作业控制必须处于非活动状态lastpipe
生效。这是默认关闭的非交互shell,并且可以在交互式shell关闭与set +m
)
shopt -s lastpipe
echo anything | tee >(gzip - > S.gz) | read S
+0
'shopt'对我来说工作得很好(虽然bashie Roger
你括注创建子shell,这不要影响外部环境中的变量。 –