我的目的是编写一个通用函数,用于通过POSIX-ly运行用于不同目的的各种文本编辑器,即将文件作为根安全地编辑。例如,如果在文件编辑过程中出现了电源丢失,则另一个示例可能会丢失SSH连接,等等。
最初是,我在我的.bash_aliases文件中为此目的定义了这些Bash函数:
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昨天,我试图推广这个解决方案,让其他Linux用户能够利用它。短暂的窥视:
# 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 "${@}"; }我用的这5位编辑。请把它作为一个例子。
由于我不应该进一步更新这个问题,所以您可以在我的Unix & Linux应答中找到这个脚本片段的最新版本。
发布于 2019-04-08 06:27:49
错误时返回非零是很好的形式。非可选选项有点难看,环境变量可能工作得更好。
一些无关的语法可以:
1之前的>&2{}不会添加任何内容echo是printf "%s\n"的别名test && echo && return不带大括号command -v为您测试有效性;无需再次测试sudoedit_internal()
{
[ $# -lt 2 ] && echo "sudoedit_internal(): Invalid number of arguments." >&2 && return 1
! command -v "$1" >/dev/null && echo "sudoedit_internal(): The editor $1 does not exist on this system." >&2 && return 1
editor="$1"; shift
SUDO_EDITOR="$editor $opt" sudoedit "$@"
}
for ed in vi nano ; do alias su$ed="opt= sudoedit_internal $ed"; done
for ed in code subl xed ; do alias su$ed="opt=-w sudoedit_internal $ed"; donehttps://codereview.stackexchange.com/questions/217005
复制相似问题