用于任意“PATH”类变量的“pathmunge”函数

vil*_*apx 2 bash

我相信你们很多人都熟悉pathmungeBourne-shell 兼容的点文件中使用的规范函数来防止PATH变量中的重复条目。我还为LD_LIBRARY_PATHMANPATH变量创建了类似的函数,因此在我的 中有以下三个函数.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 中的按引用传递?

Ale*_*exP 6

您可以使用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)

  • @AlexP 对于标记为 `bash` 的问题,`dash` 支持或不支持什么并不真正相关。 (2认同)