Shell scripting input redirection oddities

前端 未结 9 1996
不思量自难忘°
不思量自难忘° 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 <<EOF
    $result
    EOF
    echo $var1
    echo $var2
    
    0 讨论(0)
  • 2020-12-31 00:55

    The post has been properly answered, but I would like to offer an alternative one liner that perhaps could be of some use.

    For assigning space separated values from echo (or stdout for that matter) to shell variables, you could consider using shell arrays:

    $ var=( $( echo 'hello world' ) )
    $ echo ${var[0]}
    hello
    $ echo ${var[1]}
    world
    

    In this example var is an array and the contents can be accessed using the construct ${var[index]}, where index is the array index (starts with 0).

    That way you can have as many parameters as you want assigned to the relevant array index.

    0 讨论(0)
  • 2020-12-31 00:56

    My take on this issue (using Bash):

    read var1 var2 <<< "hello world"
    echo $var1 $var2
    
    0 讨论(0)
提交回复
热议问题