Is there a folder-specific .bashrc or .bash_profile?

5

2

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?

mchen.ja

Posted 2015-05-16T21:58:55.703

Reputation: 312

Not yet. But you could alias cd to read one. – ott-- – 2015-05-16T22:01:35.983

Answers

8

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'

Cyrus

Posted 2015-05-16T21:58:55.703

Reputation: 4 356

1can you explain how this works...please? :) – mchen.ja – 2015-05-17T05:23:35.137

3If 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 – 2015-05-17T05:29:41.750

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.

wrksprfct

Posted 2015-05-16T21:58:55.703

Reputation: 618