我相信你们很多人都熟悉pathmunge
Bourne-shell 兼容的点文件中使用的规范函数来防止PATH
变量中的重复条目。我还为LD_LIBRARY_PATH
和MANPATH
变量创建了类似的函数,因此在我的 中有以下三个函数.bashrc
:
# function to avoid adding duplicate entries to the PATH
pathmunge () {
case ":${PATH}:" in
*:"$1":*)
;;
*)
if [ "$2" = "after" ] ; then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
esac
}
# function to avoid adding duplicate entries to the LD_LIBRARY_PATH
ldpathmunge () {
case ":${LD_LIBRARY_PATH}:" in
*:"$1":*)
;;
*)
if [ "$2" = "after" ] ; then
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$1
else
LD_LIBRARY_PATH=$1:$LD_LIBRARY_PATH
fi
esac
}
# function to avoid adding duplicate entries to the MANPATH
manpathmunge () {
case ":${MANPATH}:" in
*:"$1":*)
;;
*)
if [ "$2" = "after" ] ; then
MANPATH=$MANPATH:$1
else
MANPATH=$1:$MANPATH
fi
esac
}
Run Code Online (Sandbox Code Playgroud)
有没有什么优雅的方法可以将这三个功能合二为一以保持我的.bashrc
文件更小?也许是一种我可以传递要检查/设置的变量的方法,类似于 C 中的按引用传递?
您可以使用eval
获取和设置知道其名称的变量的值;以下函数适用于 Bash 和Dash:
varmunge ()
{
: '
Invocation: varmunge <varname> <dirpath> [after]
Function: Adds <dirpath> to the list of directories in <varname>. If <dirpath> is
already present in <varname> then <varname> is left unchanged. If the third
argument is "after" then <dirpath> is added to the end of <varname>, otherwise
it is added at the beginning.
Returns: 0 if everthing was all right, 1 if something went wrong.
' :
local pathlist
eval "pathlist=\"\$$1\"" 2>/dev/null || return 1
case ":$pathlist:" in
*:"$2":*)
;;
"::")
eval "$1=\"$2\"" 2>/dev/null || return 1
;;
*)
if [ "$3" = "after" ]; then
eval "$1=\"$pathlist:$2\"" 2>/dev/null || return 1
else
eval "$1=\"$2:$pathlist\"" 2>/dev/null || return 1
fi
;;
esac
return 0
}
Run Code Online (Sandbox Code Playgroud)