Execute a bash function upon entering a directory

别等时光非礼了梦想. 提交于 2019-11-27 10:56:34

问题


I'd like to execute a particular bash function when I enter a new directory. Somethink like:

alias cd="cd $@ && myfunction"

$@ doesn't work there, and adding a backslash doesn't help. I'm also a little worried about messing with cd, and it would be nice if this worked for other commands which changed directory, like pushd and popd.

Any better aliases/commands?


回答1:


The easiest solution I can come up with is this

myfunction() {
  if [ "$PWD" != "$MYOLDPWD" ]; then
    MYOLDPWD="$PWD";
    # strut yer stuff here..
  fi
}

export PROMPT_COMMAND=myfunction

That ought to do it. It'll work with all commands, and will get triggered before the prompt is displayed.




回答2:


Aliases don't accept parameters. You should use a function. There's no need to execute it automatically every time a prompt is issued.

function cd () { builtin cd "$@" && myfunction; }

The builtin keyword allows you to redefine a Bash builtin without creating a recursion. Quoting the parameter makes it work in case there are spaces in directory names.

The Bash docs say:

For almost every purpose, shell functions are preferred over aliases.




回答3:


There are a few other versions of this out there, including

  • smartcd, which I wrote, and has a ton of features including templating and temporary variable saving
  • ondir, which is smaller and much simpler

Both of these support both bash and zsh




回答4:


I've written a ZSH script utilizing the callback function chpwd to source project specific ZSH configurations. I'm not sure if it works with Bash, but I think it'll be worth a try. If it doesn't find a script file in the directory you're cd'ing into, it'll check the parent directories until it finds a script to source (or until it reaches /). It also calls a function unmagic when cd'ing out of the directory, which allows you to clean up your environment when leaving a project.

http://github.com/jkramer/home/blob/master/.zsh/func/magic

Example for a "magic" script:

export BASE=$PWD # needed for another script of mine that allows you to cd into the projects base directory by pressing ^b

ctags -R --languages=Perl $PWD # update ctags file when entering the project directory

export PERL5LIB="$BASE/lib"

# function that starts the catalyst server
function srv {
  perl $BASE/script/${PROJECT_NAME}_server.pl
}

# clean up
function unmagic {
  unfunction src
  unset PERL5LIB
}


来源:https://stackoverflow.com/questions/3360738/execute-a-bash-function-upon-entering-a-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!