How to Set a Web Env Variable From the Command Line on Linux/Unix

Are you a full-stack PHP developer? Chances are that you might want to easily override an environment variable through the command-line interface.
Let’s say you are writing a bash script to automate a certain process: your Docker containers must be rebuilt, and the app’s DB_HOST
and REDIS_HOST
variables must be updated accordingly.
On such scenario, PHP frameworks like Laravel can be easily extended in order to accomplish our goal, specifically the FlexEnv package can help like this:
$ php artisan env:set NEW_KEY "your key's value"
However, if your PHP framework doesn’t have any extension to create, edit and delete .env
files via the command line, or if you just don’t want to use an extension for managing environment variables through the command line, then the sed
(stream editor) command comes to the rescue — in UNIX.
So, if your bash script needs to programmatically update the DB_HOST
variable with the value of the MySQL Docker container’s gateway IP, you’d end up writing something like this:
$ GATEWAY="$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.Gateway}}{{end}}' mysql_container)"$ sed -i "s/DB_HOST=.*/DB_HOST=${GATEWAY}/g" .env
That’s all folks! I hope you’ll find today’s tip useful.
You May Also Be Interested in…