我有几个项目在做。我宁愿在导航到该特定目录时设置别名,而不是为每个项目的位置设置别名。每个项目都是一个 git 存储库,我已经有了一种机制,可以在导航到它时将当前分支名称附加到 $PS1。
在我的 .bashrc 中,我调用一个函数:parse_git_branch 以附加到命令提示符:
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h:\w\a\]$PS1\$(parse_git_branch) "
;;
*)
;;
esac
parse_git_branch 定义在我的 .basrhc 的末尾:
function parse_git_branch {
GIT_BRANCH=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \[\1\]/')
if [[ -n $GIT_BRANCH ]];then
source $HOME/bin/cur
fi
echo $GIT_BRANCH
}
如果 GIT_BRANCH 不为空,我会获取一个简单的脚本 ~/bin/cur 来设置密码的别名:
#!/bin/bash
echo "got here!"
shopt -s expand_aliases
alias current="cd $(pwd)"
当获取 cur 时,不会设置别名。但是,调试消息确实显示正确。
我相信这是因为 shell 脚本在我当前环境的“外部”运行。从命令行调用 source cur 时设置别名。
那么,为什么在我的 .bashrc 中从“parse_git_branch”调用时没有设置别名?
谢谢!
最佳答案
这里的问题是 $() 在子 shell 中运行 parse_git_branch 的用法。结果,在打开的终端中找不到当前别名,因为父进程看不到别名。
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h:\w\a\]$PS1\$(parse_git_branch) "
source $HOME/bin/cur
;;
*)
;;
应该可以。
关于bashrc 在更改目录时不导出函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25794944/