Shell scripting input redirection oddities

前端 未结 9 1993
不思量自难忘°
不思量自难忘° 2020-12-31 00:00

Can anyone explain this behavior? Running:

#!/bin/sh
echo \"hello world\" | read var1 var2
echo $var1
echo $var2

results in nothing being o

9条回答
  •  醉梦人生
    2020-12-31 00:54

    Try:

    echo "hello world" | (read var1 var2 ; echo $var1 ; echo $var2 )
    

    The problem, as multiple people have stated, is that var1 and var2 are created in a subshell environment that is destroyed when that subshell exits. The above avoids destroying the subshell until the result has been echo'd. Another solution is:

    result=`echo "hello world"`
    read var1 var2 <

提交回复
热议问题