How can I capture text edited interactively in Vim from a shell script?
Asked by
lessons learned
I have a shell script that creates a temporary file, opens it in a new terminal with Vim, and then prints the edited contents before deleting the file. I would like to assign that resulting text to a shell variable using command substitution, but Vim does not seem to start when invoked that way. Is there a proper way to run an interactive editor and capture the edited contents, or should I leave cleanup to the calling script instead? Also, an mpv Lua plugin launches the script in a separate terminal. When mpv exits, the terminal and Vim process remain open. I expected the child process to terminate with mpv, so what is the correct way to handle that process lifetime?
Answers
Closing mpv does not automatically terminate every descendant process it started. Once the new terminal or Vim process has detached, it can continue running unless it receives a signal or is placed in a process group that you explicitly clean up. If the terminal is intentionally launched separately, have the launcher retain its PID or process-group ID and send a termination signal during cleanup; otherwise, make sure Vim stays attached to the parentโs lifecycle rather than daemonizing.
Reply to this answer
Command substitution can run interactive programs, but editors need access to a real terminal. Their input and display may involve the terminal device directly rather than just standard input and output, so redirecting the editorโs input or output to `/dev/tty` may be necessary. Another option is to use a tool such as `script` to provide a pseudo-terminal, although that can also capture terminal control sequences rather than only the edited text.
Reply to this answer
If you only need to transform text, a noninteractive tool such as `sed` or `awk` may be a better fit. But if the requirement is specifically Vimโs buffer and key bindings, those tools cannot replace it; use a terminal-aware wrapper such as `vipe` or explicitly connect Vim to a TTY.
Reply to this answer
For this use case, `vipe` from the moreutils package is probably the simplest solution. It lets you send text through Vim and receive the edited result without having to manage the temporary file yourself. You can also reproduce the same basic idea in your own script if you need custom behavior.
Reply to this answer
Add your answer
Answers are reviewed before publication.
_tomato_pruner: That approach works for automated substitutions, but it does not provide an interactive Vim-style editing buffer, so it is not equivalent when the user needs to edit manually.