My intention is to POSIX-ly write one generalized function for running various text editors I use for different purposes through sudoedit
, i.e. editing files as root safely. Safely = for instance, if a power loss occurs during the file edit; another example could be lost SSH connection, etc.
Originally, I had these Bash functions defined for this purpose in my .bash_aliases
file:
function sucode
{
export SUDO_EDITOR='/usr/bin/code --wait'
sudoedit "$@"
}
function susubl
{
export SUDO_EDITOR='/opt/sublime_text/sublime_text --wait'
sudoedit "$@"
}
function suxed
{
export SUDO_EDITOR='/usr/bin/xed --wait'
sudoedit "$@"
}
Since yesterday, I'm trying to generalize that solution for other Linux users to be able to take advantage of it. Momentary peek:
# Text editing as root; The proper way through `sudoedit`.
sudoedit_internal()
{
[ "${#}" -lt 3 ] && { printf '%s\n' 'sudoedit_internal(): Invalid number of arguments.' 1>&2; return; }
editor_path=$( command -v "${1}" )
[ -x "${editor_path}" ] || { printf '%s\n' "sudoedit_internal(): The editor path ${editor_path} does not exist on this system." 1>&2; return; }
editor_wait_option=${2}
shift 2
env SUDO_EDITOR="${editor_path} ${editor_wait_option}" sudoedit "${@}"
}
# CLI
suvi() { sudoedit_internal vi '' "${@}"; }
sunano() { sudoedit_internal nano '' "${@}"; }
# GUI
sucode() { sudoedit_internal code -w "${@}"; }
susubl() { sudoedit_internal subl -w "${@}"; }
suxed() { sudoedit_internal xed -w "${@}"; }
These 5 editors I use. Please take that as an example only.
As I should not update this question any further, you can find the up-to-date version of this script snippet in my Unix & Linux Answer.