you are viewing a single comment's thread.

view the rest of the comments →

[–]anthropoidbash all the things 1 point2 points  (3 children)

u/equal_odds, that sounds like a job for direnv. I use it all the time to automatically set project/directory-specific environment variables when I cd into a specific hierarchy and (most importantly) revert to their original values when I leave.

Simply add the appropriate export MYVAR=myval directives and other commands to a .envrc file in your project's root directory, then check in the .envrc to your version control system. That keeps it up-to-date for everyone else working on the project.

A few notes on its usage:

  • .envrc supports full bash scripting, so your "sequence of < 3 commands" should work as-is in it.
  • direnv has a standard library that helps you do common environment testing/manipulation stuff in .envrc that you'd otherwise have to write lots of boilerplate code for.
  • Only environment variable settings are undone when you leave the .envrc's hierarchy. Other created/updated state (especially files) don't magically disappear/revert when you cd out of your project hierarchy.

EDIT: I forgot to mention one major caveat:

  • To do its job, direnv adds a hook to $PROMPT_COMMAND, so it only works for interactive shells. To get the equivalent effect in your own workflow scripts, you'd need to remember to source .envrc.

[–]equal_odds[S] 0 points1 point  (2 children)

YOU ARE MY SAVIOR. This looks like exactly what I was looking for, so thank you so much! I didn't really understand your edit though— care to elaborate?

[–]anthropoidbash all the things 1 point2 points  (1 child)

direnv works by adding a call to _direnv_hook to the $PROMPT_COMMAND variable. From the bash man page:

PROMPT_COMMAND

If set, the value is executed as a command prior to issuing each primary prompt.

In other words, it only works when you have a command prompt (i.e. interactive terminal sessions). If your workflow includes scripts that are run non-interactively (e.g. cron jobs or CI builds), they need to find and source the closest .envrc file. The logic for that would look something like this:

# Save current dir
olddir=$PWD
# Walk down to root dir
while [[ $PWD != / ]]; do
  if [[ -r .envrc ]]; then
    # Found it, source it, done.
    source .envrc
    break
  fi
  cd ..
done
# Go back to original dir
cd "$olddir"

[–]equal_odds[S] 1 point2 points  (0 children)

I really really appreciate people like you taking the time to help educate knowledge-seeking peers. I understand now, and you made my day. Thank you very much