在pipleline中分配变量

时间:2015-07-09 09:20:49

标签: bash command-line zsh

我正在尝试将stdin存储到管道中的变量中:

$ echo 'message' | variable="-" ; echo $variable

我知道我可以为此做一个剧本;但我只想这样理解。

知道为什么这不起作用吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

echo 'message' | ( var="$(< /dev/stdin)"; echo "$var" )

或者:

echo 'message' | { var="$(< /dev/stdin)"; echo $var; }

注意:( ... )在管道之后打开另一个新的子shell。

<小时/> 另一种方式(使用lastpipe bash >=4.2):

set +m;shopt -s lastpipe  # set +m disables job control
echo "hello world" | read test; echo test=$test
echo "hello world" | test="$(</dev/stdin)"; echo test=$test

Bash Manual says

  

lastpipe

     

如果设置,作业控制未激活,则shell运行最后一个命令   当前shell中后台未执行的管道   环境。

请注意,默认情况下,非交互式shell中的作业控制处于关闭状态。