移动到另一个目录时,我可以使用.bashrc吗?

时间:2014-10-10 13:55:08

标签: linux bash unix

就像.bash_profile在初始命令提示符之前配置我的shell一样,并且类似地.bashrc为每个新终端运行的地方,当我移动到另一个目录时,我可以有一个等价物吗?

理想情况下,只有当我进入某个目录时才设置env变量,设置别名等的bash函数?

3 个答案:

答案 0 :(得分:2)

你可以让cd成为一个函数,并让它检测你是否输入了那个特定的目录。

cd () {
  builtin cd "$@"
  case $PWD in
    /some/directory) . ./profilefile;;
  esac
}

我不推荐这种方法,因为这意味着即使您因为与项目工作无关的某些原因进入该目录,脚本也会被执行。我建议使用一个特定的函数来更改项目目录并获取设置脚本。

myproj () {
  cd /some/directory && . ./profilefile
}

答案 1 :(得分:1)

对于交互式会话,pgl有正确的想法。以下是使用PROMPT_COMMAND

的示例
$ cat foo
set_environment() {
  case "$PWD/" in
    /tmp/* )
      alias whatshere='echo "Only junk"'
      ;;
    /etc/* )
      alias whatshere='echo "Config files: " *'
      ;;
    * )
      unalias whatshere 2> /dev/null
  esac
}

PROMPT_COMMAND='set_environment'

$ source foo

$ cd ~
$ whatshere
bash: whatshere: command not found    

$ cd /tmp    
$ whatshere 
Only junk  

$ pushd /etc/apache2  # Also works when not using cd
/etc/apache2 /tmp
$ whatshere
Config files:  apache2.conf conf.d envvars magic  (...)

答案 2 :(得分:0)

我不知道任何Bash功能可以执行您所描述的操作。 但是你可以通过在cd

上创建别名(或函数)来欺骗
alias cd='echo Yooo ; cd'

或更好(别名对于避免无限循环很重要......)

_cd() { if [ "$1" == 'toto' ]; then export TOTO=1; fi ; cd "$1"; }
alias cd="_cd"