我正在尝试将stdin
存储到管道中的变量中:
$ echo 'message' | variable="-" ; echo $variable
我知道我可以为此做一个剧本;但我只想这样理解。
知道为什么这不起作用吗?
答案 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
lastpipe
如果设置,作业控制未激活,则shell运行最后一个命令 当前shell中后台未执行的管道 环境。
请注意,默认情况下,非交互式shell中的作业控制处于关闭状态。