김동우 김동우 - 6 months ago 19
Bash Question

How can I use vi command in shell script?

I am using CentOS 6.7

I want open test.txt by vi and insert text "hihi"
then save and quit from vi.

#! /bin/bash

vi test.txt << 'END'
i
hihi
press ESC
w
q
END


The result like this

Vim: Warning: Input is not from a terminal
Vim: Error reading input, exiting...
Vim: preserving files...
Vim: Finished.


How can I fix it?

Answer

There are many ways to create or modify text files, ranging from cat, to sed, to awk, to ed. I am going to assume, though, that you have a good reason for wanting to use vi.

Try this command:

echo $'ihihi\E:x\n' | vi test.txt

In operation, this looks like:

$ echo $'ihihi\E:x\n' | vi test.txt
Vim: Warning: Input is not from a terminal
$ cat test.txt
hihi

I found this approach to be fragile: if vi experiences an error condition, no message will be seen.

How it works

We need to get vi to see an escape character. There are many ways to do that. I chose to use bash's $'...' strings as it allows escape to be entered as a simple two character string: \E. The steps that we use are:

  1. i introduces insert mode.

  2. The four characters hihi are entered into the buffer.

  3. Escape, \E, exits insert mode.

  4. :x\n exits with save.

Comments