Run different Linux program based on current directory (using Bash shell)

Sometimes I want to use a specific version of a program, depending on the directory I’m currently in. With no obvious solution from Stack Overflow, I’ll document my own.

I find this useful for my infrastructure as code configuration with terraform. Each directory is a different environment or site, and I can use different versions of terraform based on the name of the directory.

This is for bash shell on Linux. Tested on bash version 4.3 or newer. Might work on older version too.

Add this code to your .bashrc file:

function terraform () {
  case "${PWD##*/}" in
    *env-2023*) ~/terraform_1.6.2 "$@";;
    *) ~/terraform_0.11.15 "$@";; # default case
  esac
}

Then log out and log back in.

What is this doing?

When you run the command “terraform”, your current directory is checked. If you are in a directory that has “env-2023” anywhere in it, then terraform_1.6.2 will run. Otherwise the (really) old version will run.

Conclusion

With this in your .bashrc file, you can have multiple directory patterns in the case syntax, each running a specific version of an application. I find this helpful when in the process of upgrading terraform config for all of my different environments for my infrastructure as code.

Here are some more Linux related posts.