Bash中使用相对路径source配置文件失败的问题求助
Bash中使用相对路径source配置文件失败的问题求助
我最近在折腾自己的dotfiles仓库,想实现一个挺简单的需求:不管把仓库克隆到系统的哪个位置,只要在shell的配置文件(比如.zshrc/.bashrc)里source仓库里对应的default-config文件,这个default-config就能自动用相对路径加载同目录下的其他配置文件,完全不用硬编码绝对路径。
Zsh那边已经完美跑通了,但Bash这边死活不行,实在搞不懂哪里出问题了,来求助各位大佬!
先交代下我的仓库结构:
.dot-files/ ├─ bash/ │ ├─ default-config │ ├─ .alias、.git-prompt等一堆配置文件 ├─ zsh/ │ ├─ default-config │ ├─ .alias、.git-prompt.sh等一堆配置文件
Zsh的情况(完全正常)
我的.zshrc里就一行:
source ~/.dot-files/zsh/default-config
然后zsh/default-config里是这么写的:
source "$(dirname "$0")/.alias" source "$(dirname "$0")/.prompt" source "$(dirname "$0")/.zsh-git-info" source "$(dirname "$0")/.git-prompt.sh"
启动Zsh完全没问题,所有配置都能正常加载,$(dirname "$0")能正确解析出default-config所在的目录路径,转换成绝对路径后source对应的文件。
Bash的情况(报错找不到文件)
我的.bashrc里同样是一行:
source ~/.dot-files/bash/default-config
bash/default-config里的写法是:
source "$(dirname -- "$0")/.git-prompt" source "$(dirname -- "$0")/.ps1" source "$(dirname -- "$0")/.alias" source "$(dirname -- "$0")/.utils"
结果启动Bash的时候直接报错:
-bash: ./.git-prompt: No such file or directory -bash: ./.ps1: No such file or directory -bash: ./.alias: No such file or directory -bash: ./.utils: No such file or directory
我的核心需求
- 切换到Bash后(执行
chsh -s /bin/bash重启终端)配置能自动生效 - 任何人克隆这个仓库到任意位置,只需要在自己的
.bashrc/.zshrc里source对应shell的default-config就行,完全不用关心仓库内部的文件结构 default-config必须用相对路径加载同目录(或仓库内其他子目录)的文件,绝对不能写死硬编码的路径
Zsh里source "$(dirname "$0")/xxx"的逻辑明明能正常工作,为什么Bash就不行?有没有其他办法能实现我想要的效果?
备注:内容来源于stack exchange,提问作者Kalec
相关产品推荐
相关产品推荐

