当我尝试read在Bash中使用这样的命令时:
echo hello | read str
echo $str
什么都没有回应,而我认为str应该包含字符串hello.任何人都可以帮我理解这种行为吗?
jpa*_*cek 57
该read脚本中的命令是好的.但是,您在管道中执行它,这意味着它在子shell中,因此,它读取的变量在父shell中不可见.你也可以
在子shell中移动脚本的其余部分:
echo hello | { read str
  echo $str
}
或使用命令替换从子shell中获取变量的值
str=$(echo hello)
echo $str
或稍微复杂的例子(抓住ls的第二个元素)
str=$(ls | { read a; read a; echo $a; })
echo $str
gle*_*man 39
其他不涉及子shell的bash替代方案:
read str <<END             # here-doc
hello
END
read str <<< "hello"       # here-string
read str < <(echo hello)   # process substitution
典型用法可能如下所示:
i=0
echo -e "hello1\nhello2\nhello3" | while read str ; do
    echo "$((++i)): $str"
done
和输出
1: hello1
2: hello2
3: hello3