首页 > 解决方案 > 这里是与VI交互的文档

问题描述

我只是想弄清楚 EOF 和这里的文件。我在网上读到一些看起来很酷的想法,我可以扩展它。它应该创建一个文本文件,并向其中添加文本,所有这些都使用此处的文档。语法如下:

#!/bin/sh
filename=test.txt
vim $filename <<EndOfCommands
i
This file was created automatically from
a shell script.
^[
ZZ
EndOfCommands

现在不幸的是,我从中得到了一个错误:

./EOF.sh 
Vim: Warning: Input is not from a terminal
Vim: Error reading input, exiting...

Vim: Finished.

任何人都可以帮助解决此错误吗?我还假设 ^[ 代表被按下的退出按钮?

标签: bashshellvimviheredoc

解决方案


vi并且vim旨在在终端中以交互方式使用,而不是编写脚本。

使用ed相反,它可以愉快地接受来自所有类型的标准输入源的输入:

#!/bin/sh
filename=test.txt
ed -s "$filename" <<EndOfCommands
i
This file was created automatically from
a shell script.
.
w
EndOfCommands

(在插入模式下,带有单个句点的行表示输入结束并返回命令模式,有点像转义vi(m)。)

使用ex是另一种选择;在已安装的系统上,vim它通常是它的非可视版本。


推荐阅读