Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic environment variables in Linux?

Is it possible in some way to have dynamic environment variables in Linux?

I have a webserver where sites follow this layout:

site/
    qa/
    production/

I would like to have an environment variable (e.g. APPLICATION_ENV) that is set to "qa" when I'm in the qa directory, and to "production" when I'm in the production directory. The reason for this is that various sites can use many different processes that all need to know if it's the QA or production environment. Some sites use PHP under Apache, some use Node.js, some sites come with commandline tools, cron jobs, etcetera. I would like to have one authorative source on whether it's a QA or a production environment.

like image 803
Sander Marechal Avatar asked Jun 14 '26 16:06

Sander Marechal


2 Answers

Based on rvm's override:

cd () { 
    if builtin cd "$@"
    then
        if [[ "$PWD" =~ /(qa|production)(/|$) ]]
        then
            export APPLICATION_ENV="${BASH_REMATCH[1]}"
        else
            unset APPLICATION_ENV
        fi
        return 0
    else
        return $?
    fi
}

Just put this function in .bashrc or some other sourced environment file, and try to cd into qa, production, or one of their subdirectories.

like image 64
l0b0 Avatar answered Jun 16 '26 06:06

l0b0


You can create an executable script in one of /bin or /usr/bin directories and execute it from the site scripts. I don't see why you need to hack cd.

/usr/bin/which-version:

#!/bin/bash
if [[ "$PWD" =~ /(qa|production)(/|$) ]]
then
  echo "${BASH_REMATCH[1]}"
else
  echo "unknown"
fi

web-site:

$env = system("which-version")

like image 39
perreal Avatar answered Jun 16 '26 07:06

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!