12

Is it possible to have a bash script (like a .bashrc or .bash_profile, basically) that is executed only upon cd’ing into a specific folder?

1
  • Not yet. But you could alias cd to read one.
    – ott--
    May 16, 2015 at 22:01

3 Answers 3

13

Add this to your ~/.bashrc.

If .bashrc is located in current working directory:

PROMPT_COMMAND='if [[ "$bashrc" != "$PWD" && "$PWD" != "$HOME" && -e .bashrc ]]; then bashrc="$PWD"; . .bashrc; fi'
4
  • 2
    can you explain how this works...please? :)
    – user291415
    May 17, 2015 at 5:23
  • 4
    If variable $PROMPT_COMMAND is set, the value is executed as a command prior to issuing each primary prompt. In this case it makes three tests before .bashrc in current working directory is sourced.
    – Cyrus
    May 17, 2015 at 5:29
  • This seemed to break my bash config, after adding this line to my ~/.bashrc file, upon opening a new terminal window my prompt and all my bashrc config in my home dir bashrc wasn't applied (I got the default prompt, etc). Jan 18, 2022 at 17:24
  • Although this works it also pollutes your bash process with (exported) variables, aliases and functions that you might not want to keep around when changing to a different directory. I spent some time solving that by spawning a new bash process when a local bashrc is found. See github.com/bas080/dotlocaldotbashrc
    – bas080
    Jan 4 at 18:49
2

Depending on your exact use case and constraints, ondir may suit your needs:

ondir is a small program to automate tasks specific to certain directories. It works by executing scripts in directories when you enter and leave them.

It does this by using a central ~/.ondirrc file for per-dir configuration. In contrast, the clever PROMPT_COMMAND setup that @Cyrus suggested allows for the config to reside in the individual directories themselves. Each approach is valid; it depends on the constraints and data you're dealing with.

Disclaimer: I've never used ondir personally. I came across it while looking for an automatic way to handle git user config per-dir. In that case, ondir didn't fit my needs—I ended up using a git alias passing --config options to git clone.

0

addition from @Cyrus answer, if you use zsh, you need to use precmd() :

PROMPT_COMMAND='if [[ "$profile" != "$PWD" && "$PWD" != "$HOME" && -e .profile ]]; then profile="$PWD"; source .profile; fi'
precmd() { eval "$PROMPT_COMMAND" }

it's answered from this answer

nb: my prompt tests for .profile not .bashrc.

You must log in to answer this question.