Skip to content

env#

Environment and project helpers.

Functions#

  • get_project_root
  • Purpose: Determine project root as the parent directory of the top-level calling script directory.
  • Behavior: Walks the BASH_SOURCE stack from the outermost caller to find a real script file; falls back to CWD when none is found (e.g., interactive shell).

  • load_env [env_file=.env]

  • Purpose: Load environment variables from a dotenv file; exports them for the current shell.
  • Args: env_file - path to a .env file; default .env in CWD.
  • Behavior: Sources the file with allexport on; a caller that already had allexport on keeps it on afterwards.

  • require_env VAR [VAR...]

  • Purpose: Ensure variables are set; errors with list of missing variables and returns non-zero if any missing.

  • resolve_env_value key default [env_file=.env]

  • Purpose: Resolve a value from the current environment or from a dotenv file; falls back to a default.
  • Args:
    • key - variable name to resolve.
    • default - value when not set anywhere.
    • env_file - path to search when not present in the environment.
  • Parsing: the value is everything after the first =. A value in double or single quotes is the text between them (# inside is literal; in double quotes \" and \\ are unescaped); a comment may follow the closing quote. An unquoted value ends at a # that follows whitespace (ab#cd is a value); a value that starts with # (KEY=#x) is read as empty and returns the default, although the shell and dotenv read #x. Leading/trailing whitespace and a trailing CR are trimmed. Internal whitespace and backslashes are kept as written. Text after a closing quote that is not a comment makes the value unquoted, with a stray leading and trailing quote dropped: E='it''s' returns it''s, not the shell's its.
  • Environment: a value taken from the environment goes through the same parser as one read from the file, so KEY='"x" # c' in the environment resolves to x.
  • Output: printed with printf '%s\n', so values such as -n survive.

  • run_superuser_setup

  • Purpose: Execute scripts/superuser.sh in the project root.
  • Behavior: Returns non-zero and logs an error if the script is missing or not executable.

  • init_include

  • Purpose: Convenience initializer: sets traps (if available), cd to project root, and loads .env.
  • Behavior: Calls setup_traps when imported; prints debug logs when DEBUG=true.

  • env_set_value file KEY value

  • Purpose: Set KEY in an env file: the line is replaced where it is (an export prefix included), or appended; a key written twice ends as one line. The file is created, mode 600, when missing.
  • Behavior: The value is written bare when it can be, else quoted so the shell and python-dotenv read it the same; one that cannot be is refused. Written in place, not moved, so a symlinked .env keeps pointing at its target.
  • Returns: 0 written; 1 a bad key, a newline in the value, a value that cannot be quoted, or a failed write.