bash 当stdin来自`cat` bash时读取完整的stdin直到EOF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32091717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read full stdin until EOF when stdin comes from `cat` bash
提问by edi9999
I'm trying to read full stdin into a variable :
我正在尝试将完整的标准输入读入一个变量:
script.sh
脚本文件
#/bin/bash
input=""
while read line
do
echo "$line"
input="$input""\n""$line"
done < /dev/stdin
echo "$input" > /tmp/test
When I run ls | ./script.sh
or mostly any other commands, it works fine.
当我运行ls | ./script.sh
或大多数其他命令时,它工作正常。
However It doesn't work when I run cat | ./script.sh
, enter my message, and then hit Ctrl-C to exit cat.
但是,当我运行时它不起作用cat | ./script.sh
,输入我的消息,然后按 Ctrl-C 退出 cat。
Any ideas ?
有任何想法吗 ?
回答by Roberto Reale
I would stick to the one-liner
我会坚持单线
input=$(cat)
Of course, Ctrl-D
should be used to signal end-of-file.
当然,Ctrl-D
应该用来表示文件结束。