Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

What is the best way to execute a script when entering into a directory?
When I move into a new directory I would like bash to execute the projectSettings.bash script much like RVM does.

share|improve this question
2  
Into every directory, or selected ones? And the same script for each, or not? –  enzotib Sep 24 '11 at 19:50
    
Every directory. The script in the directory named projectSettings.bash if it exists. –  James Andino Sep 24 '11 at 19:54
add comment

1 Answer

up vote 21 down vote accepted

You can make cd a function, and make it detect if you enter that particular directory.

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

Do not do this in directories that you haven't whitelisted, because it would make it very easy for someone to trick you into running arbitrary code — send you an archive, so you unzip it, change into the directory it created, and you've now run the attacker's code.

I don't recommend this approach, because it means the script will be executed even if you enter that directory for some reason that's unrelated to working on the project. I suggest having a specific function that changes to the project directory and sources the settings script.

myproj () {
  cd /some/directory && . ./projectSettings.bash
}
share|improve this answer
    
I only started in Ruby a little while ago. The RVM tool tho is completely in Bash and one of the best pieces of Bash magic I have seen. I think the answer is a little silly because one of the absolutely worse things you can ever do is over ride something like cd and there is with out doubt a better way. Even using $PROMPT_COMMAND is better! –  James Andino Oct 2 '11 at 23:21
    
@JamesAndino In zsh I'd use chpwd. Lacking an exact equivalent in bash, overloading cd feels reasonable. With PROMPT_COMMAND, your per-directory settings will be set later if you run cd foo; somecommand and not at all if you run (cd foo; somecommand) (this may or may not be what you want). –  Gilles Oct 2 '11 at 23:34
    
They do it here using just BASH with out overloading PROMPT_COMMAND or cd github.com/wayneeseguin/rvm I tried to unlock the secret but failed. –  James Andino Oct 3 '11 at 13:16
    
I was completely wrong and apologize. RVM was overloading cd. –  James Andino Oct 7 '11 at 14:22
1  
(removed some tangential pro/anti-Ruby stuff from this comment thread) –  Michael Mrozek Jul 25 '12 at 21:04
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.