2

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?

phd
  • 82,685
  • 13
  • 120
  • 165
wesm
  • 451
  • 6
  • 14
  • 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 Answers1

6

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.)

filbranden
  • 8,522
  • 2
  • 16
  • 32
  • 1
    Would 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
    Cool. Thanks for the validation. – wesm Mar 01 '20 at 03:47
  • 3
    On zsh, include a `=` to turn on word splitting: `${=VISUAL:-${EDITOR:-vi}` – Carl Walsh Jul 31 '20 at 21:46