Shell scripting input redirection oddities

前端 未结 9 2130
不思量自难忘°
不思量自难忘° 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:44

    Allright, I figured it out!

    This is a hard bug to catch, but results from the way pipes are handled by the shell. Every element of a pipeline runs in a separate process. When the read command sets var1 and var2, is sets them it its own subshell, not the parent shell. So when the subshell exits, the values of var1 and var2 are lost. You can, however, try doing

    var1=$(echo "Hello")
    echo var1
    

    which returns the expected answer. Unfortunately this only works for single variables, you can't set many at a time. In order to set multiple variables at a time you must either read into one variable and chop it up into multiple variables or use something like this:

    set -- $(echo "Hello World")
    var1="$1" var2="$2"
    echo $var1
    echo $var2
    

    While I admit it's not as elegant as using a pipe, it works. Of course you should keep in mind that read was meant to read from files into variables, so making it read from standard input should be a little harder.

提交回复
热议问题