Using my .bash_profile, I used to change my iTerm2 profile per machine with the following command:

echo -e "\033]50;SetProfile=ssh\a"

Now, I want to change it depending on my current working directory.

Ideally must work something like this:

  • Once I enter /mnt/production or any subfolder inside, iTerm should change to production profile.
  • Once I leave that directory, should change to bash profile.

Is there any way of doing that?

1 Answer 1


Finally I found a solution using bash-preexec.

That utility have the following function:

precmd Executed just before each prompt. Equivalent to PROMPT_COMMAND, but more flexible and resilient.

To install bash-preexec:

brew install bash-preexec

Then I have to add the following to my .bash_profile:

if [ -f $(brew --prefix)/etc/profile.d/bash-preexec.sh ]; then
    . $(brew --prefix)/etc/profile.d/bash-preexec.sh
    precmd() {
        if [[ $PWD == /mi/prod/path/produccion* ]]; then
            if [ -z $shouldChangeProfile ]; then
                echo -e "\033]50;SetProfile=production\a"
        elif [ "$shouldChangeProfile" == "1" ]; then
            echo -e "\033]50;SetProfile=bash\a"
            unset shouldChangeProfile

Inside the precmd function is where I change the profile according to my needs.

shouldChangeProfile prevents unnecessary profile changes.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .