LoginSignup
1
1

More than 5 years have passed since last update.

関数「greppath」を作って、環境変数PATHにパスが含まれていない時だけPATHにパスを追加する

Last updated at Posted at 2012-12-26

コードは以下の通りです。

~/.bashrc
function greppath() {
    local FOUND=0
    local IFS=':'
    local DIR
    for DIR in ${2}; do
        [ "${1}" == "${DIR}" ] && FOUND=1
    done
    [ ${FOUND} -ge 1 ] && echo "${1}" && return 0 || return 1
}

使用例その1。

~/.bashrc
if [ -d "${HOME}/bin" ] ; then
    if ! greppath "${HOME}/bin" "${PATH}" 2>&1 > /dev/null; then
        PATH="${PATH}:${HOME}/bin"
    fi
fi

使用例その2。

~/.bashrc
if [ -x /usr/local/bin/brew ]; then
    COREUTILS="$(/usr/local/bin/brew --prefix coreutils)"
    if [ -n "${COREUTILS}" ]; then
        GNUBIN="${COREUTILS}/libexec/gnubin"
        if ! greppath "${GNUBIN}" "${PATH}" 2>&1 > /dev/null; then
            PATH="${GNUBIN}:${PATH}"
        fi
        unset GNUBIN
    fi
    unset COREUTILS
fi

~/.bash_profileと~/.bashrcのどちらに書くか、は悩ましいところです、Emacsから呼び出すこともあることを考えると~/.bashrcがよいように思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1