How to invoke "EDITOR" environment variable to open/edit file, in a secure way?

Viewed 1224

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?

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

Related