Is there a way to use the EDITOR or VISUAL environment variables in a bash script to edit a given file using the editor of the users choice?
-
Does this answer your question? [How to open the default text editor in Linux?](https://stackoverflow.com/questions/19252791/how-to-open-the-default-text-editor-in-linux) – phd Feb 29 '20 at 16:59
-
https://stackoverflow.com/search?q=%5Bshell%5D+EDITOR+VISUAL+environment+variable – phd Feb 29 '20 at 16:59
1 Answers
You can use the following:
${VISUAL:-${EDITOR:-vi}} "${filename}"
This will use the VISUAL
variable if it's set, otherwise EDITOR
, and if neither is set it will fallback to vi
.
You can use a different fallback if you like. In particular, Debian-based distros typically ship a binary named editor
that system administrators can control to set a system-wide default editor as a fallback...
vi
is typically ubiquitous, so it's probably an appropriate default to use.
Note that the variables are unquoted here. This is unfortunately necessary, since an EDITOR
or VISUAL
setting can include command arguments, so supporting word splitting is required.
For example, one might use EDITOR="emacs -nw"
to force the use of Emacs on the terminal (rather than the window system), or EDITOR="vim -u $HOME/.vim/custom-vimrc"
to have Vim use a custom configuration when launched by external programs.
UPDATE: Reversed the order to try $VISUAL
first, then $EDITOR
, since that seems to be the most common setup (e.g. Mutt mail client, git, etc.)

- 8,522
- 2
- 16
- 32
-
1Would it be recommended to try VISUAL first? As a developer, what are your expectations? – wesm Feb 29 '20 at 19:25
-
@wesm https://unix.stackexchange.com/q/4859/281844 but I've seen programs that try `$EDITOR` first as well. I guess these days it's rare to have `$VISUAL` even set... And when it is, it's usually set to the same as `$EDITOR`. – filbranden Feb 29 '20 at 22:07
-
@wesm Actually, just reversed the order in my answer. Now thinking about it, `$VISUAL` first makes more sense. Also, it's what both `mutt` and `git` do, so I'll trust what the authors of those tools decided to use. – filbranden Feb 29 '20 at 22:19
-
1
-
3On zsh, include a `=` to turn on word splitting: `${=VISUAL:-${EDITOR:-vi}` – Carl Walsh Jul 31 '20 at 21:46