我已经搜索过这个错误,但找不到解决方案。
我正在按照加入 Linux 世界的基本指南,尝试创建 .txt
文件,使用该脚本在 Vim 中添加一些文本行。它应该有效,但对我而言无效。
这是我的简单脚本(我正在使用 zsh
,如果它可能是重要信息的话):
#!/bin/sh
filename= test.txt
vim $filename << COMMAND
i
Hello
^[
:x
COMMAND
脚本失败并显示消息:Vim: error reading input
。
我哪里错了?
最佳答案
filename
变量的赋值中有一个拼写错误(一个额外的空格):filename= test.txt
。此表达式被解释为使用设置为空字符串的filename
环境变量调用test.txt
命令。所以你应该删除 =
之后的空格。
关于 Error reading input 消息,请阅读 Vim 文档::help E208
:
Vim: Error reading input, exiting...
This occurs when Vim cannot read typed characters while input is required. Vim got stuck, the only thing it can do is exit. This can happen when both stdin and stderr are redirected and executing a script that doesn't exit Vim.
所以 Vim 认为它读取了一个没有退出 Vim 的脚本。您的脚本进入插入模式,输入 Hello
,然后输入 Esc,最后调用 :x
命令。一切都很好,:x
命令退出 Vim,当然,如果它是在命令行区域输入的话。如果您输入 ^[
作为 Control - V, Esc,脚本将退出插入模式并且成功执行了 :x
命令。因此,您输入了 ^[
作为两个字符。所以你真正的输入是 Hello^[:x
(脚本没有退出 Vim):
Vim: Warning: Input is not from a terminal
Vim: Error reading input, exiting...
Vim: preserving files...
Vim: Finished.
现在,如果用实际的转义字符替换两个字符 ^[
,并从同一目录执行脚本,由于交换文件,它将失败:
Vim: Warning: Input is not from a terminal
Vim: Error reading input, exiting...
Vim: Finished.
(您可以通过运行 vim test.txt
阅读详细说明)。你可以使用 -n
选项忽略交换文件:vim -n "$filename"
。现在输出将是:
Vim: Warning: Input is not from a terminal
这是有道理的。你实际上不需要 Vim 的交互式版本。所以你应该使用 ex 模式(-e
选项),或者更确切地说是改进的 ex 模式(-E
选项): vim -n -E "$filename"
.
如果内容不应该被解释,将值用单引号括起来也是一个好主意,如果字符串包含 shell 变量,则用双引号括起来:filename='test.txt'
.
固定版本:
filename='test.txt'
vim -n -E "$filename" << COMMAND
i
Hello
^[
:x
COMMAND
(^[
在 Vim 中使用 Control - v, Esc 输入)。
关于bash - Vim:读取输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40319486/