让 Bash 文件遵循 XDG Base Directory Spec

所有的步骤思路来自这篇博客。

步骤

首先在 /etc/bash.bashrc 末尾追加:

[!WARNING]
如果是其他发行版, 这个文件名或原始内容可能会有所区别, 因此可能不可直接套用。

# To make bash follow the XDG Base Directory specification
confdir=${XDG_CONFIG_HOME:-$HOME/.config}/bash
statedir=${XDG_STATE_HOME:-$HOME/.local/state}

# Source settings file
[ -f "$confdir/bashrc" ] && . "$confdir/bashrc"

# Change the location of the history file
HISTFILE="$statedir/bash_history"

unset confdir
unset statedir

其次, 在 /etc/profile.d/ 目录下添加一个 bash-xdg-dir.sh, 其内容如下:

confdir=${XDG_CONFIG_HOME:-$HOME/.config}/bash
statedir=${XDG_STATE_HOME:-$HOME/.local/state}

# Source settings file
if [ -d "$confdir" ]; then
    for f in bash_profile bashrc; do
        [ -f "$confdir/$f" ] && . "$confdir/$f"
    done
fi

# Change the location of the history file
HISTFILE="$statedir/bash_history"

unset confdir
unset statedir

这样无论 Bash 登录(login) 还是交互(interactive) 都会支持读取对应位置的文件了啦。
之后, 你可以参照下面这个表格, 将你 $HOME 下与 Bash 相关的文件移动/重命名为对应的文件。

Default XBDS
~/.bashrc ~/.config/bash/bashrc
~/.bash_profile ~/.config/bash/bash_profile
~/.bash_history ~/.local/state/bash_history

不过, 由于不是源码层面上的补丁, 因此 bash 还是会优先尝试读取 $HOME 下的这些文件, 因此确保它们都被移动了。

结语

最后,我顺便写了一个 PKGBUILD 可以自动完成上述的这些步骤, 仓库地址在 voidNan/bash-xdg-dir-patch。

不过比起这些,我更希望这个补丁最终被上游合并。

2 Likes