首页 > 解决方案 > 在 bash 中从标准输入获取交互式、多行、格式化输入

问题描述

我希望能够以类似于 hereDOC 的方式从终端交互式获取输出。即我希望用户能够键入多行,然后将该信息传递到一个文件中,并保留所有格式。像这样的东西。

echo  "Type your message below. To finish the letter type DONE by itself on a line"
file=mktmp
cat << DONE > $file

显然这不起作用,因为在 DONE 之前找到了 EOF。我考虑过将用户传递给 VIM 之类的东西,但我不太懂电脑的同事很难使用 vim/emacs/nano。

标签: bashuser-interfacestdin

解决方案


好的,所以我想出了这个,但请帮助我找到更好的东西或改进它。

echo  "Type your message below, to finish the letter press CTL+D"
mapfile message
file=`mktemp`
for x in `seq 0 ${#message[@]}`
        do printf "${message[$x]}" >> $file
done
cat $file

推荐阅读