Shell scripting input redirection oddities

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

    It's because the pipe version is creating a subshell, which reads the variable into its local space which then is destroyed when the subshell exits.

    Execute this command

    $ echo $$;cat | read a
    10637
    

    and use pstree -p to look at the running processes, you will see an extra shell hanging off of your main shell.

        |                       |-bash(10637)-+-bash(10786)
        |                       |             `-cat(10785)
    

提交回复
热议问题