dash-shell

Shell scripting input redirection oddities


Can anyone explain this behavior? Running:

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

results in nothing being ouput, while:

#!/bin/sh
echo "hello world" > test.file
read var1 var2 < test.file
echo $var1
echo $var2

produces the expected output:

hello
world

Shouldn't the pipe do in one step what the redirection to test.file did in the second example? I tried the same code with both the dash and bash shells and got the same behavior from both of them.


Solution

  • A recent addition to bash is the lastpipe option, which allows the last command in a pipeline to run in the current shell, not a subshell, when job control is deactivated.

    #!/bin/bash
    set +m      # Deactiveate job control
    shopt -s lastpipe
    echo "hello world" | read var1 var2
    echo $var1
    echo $var2
    

    will indeed output

    hello
    world