如何在Bash中使用read命令?

Det*_*ant 53 bash built-in

当我尝试read在Bash中使用这样的命令时:

echo hello | read str
echo $str
Run Code Online (Sandbox Code Playgroud)

什么都没有回应,而我认为str应该包含字符串hello.任何人都可以帮我理解这种行为吗?

jpa*_*cek 57

read脚本中的命令是好的.但是,您在管道中执行它,这意味着它在子shell中,因此,它读取的变量在父shell中不可见.你也可以

  • 为什么"读一个;读一个;" 要求*两次*? (5认同)

gle*_*man 39

其他不涉及子shell的bash替代方案:

read str <<END             # here-doc
hello
END

read str <<< "hello"       # here-string

read str < <(echo hello)   # process substitution
Run Code Online (Sandbox Code Playgroud)

  • 您也可以使用here字符串的过程,例如`read ABC <<< $(echo'aaa bbb ccc')` (2认同)

Shi*_*zmo 8

典型用法可能如下所示:

i=0
echo -e "hello1\nhello2\nhello3" | while read str ; do
    echo "$((++i)): $str"
done
Run Code Online (Sandbox Code Playgroud)

和输出

1: hello1
2: hello2
3: hello3
Run Code Online (Sandbox Code Playgroud)