bash 配置

bash 的两个配置文件

login 时只加载 .bash_profile(如果存在),其他时候只加载 .bashrc

最好是把内容放在 .bashrc,然后让 ~/.bash_profile 去 source ~/.bashrc

虽然 ~/.bashrc 是所有非登陆的 bash 都会读,但默认的 ~/.bashrc 的开头检查了当前是否为交互终端,如果不是则退出。如果非要绕过这个限制,可以强制一个终端为交互终端:bash -i

Windows 的 Cygwin 目录下自己有 home。因此要让它的 ~/.bashrc 去 source Windows 用户目录的 ~/.bashrc,不然会出现两处配置不一致的情况。

bash 显示 git 分支

parse_git_branch() {
    if ! [[ $(git rev-parse --is-bare-repository 2>/dev/null) == true ]]; then
        local BRANCH="$(git branch 2>/dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')"
        [[ "${BRANCH}" == "" ]] && return 0
        local MSG="$(git status 2> /dev/null | tail -n1)"
        if [[ "$MSG" != "nothing to commit"* ]]; then
            echo -n "(${BRANCH}*) "
        else
            echo -n "(${BRANCH}) "
        fi
    fi
}
EXITCODE='$(code=$?; if (( code )); then echo -ne "\[\e[91m\][$code]\[\e[00m\] "; fi)'
export PS1="${EXITCODE}\u \[\e[32m\]\w \[\e[00m\]\[\e[91m\]\$(parse_git_branch)\[\e[00m\]$ "