Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set a bash variable with environment variables?

I have environment variables

POSTGRES_USER=dbuser
POSTGRES_PASS=dbpasswd
POSTGRES_DBNAME=db
POSTGRES_HOST=123.123.123.123
POSTGRES_PORT=5432

I want to use them in bash script to declare a variable

#!/usr/bin/env bash
DATABASE_URL="postgres://$POSTGRES_USER:$POSTGRES_PASS@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DBNAME"

How do I properly import my environment variables directly to my bash variable DATABASE_URL?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If POSTGRES_USER, etc. were environment variables, then what you have should work. If what you have is not working, I assume that POSTGRES_USER, etc. are not environment variables. You don’t need to (and indeed cannot) "import" them in the script; you need to export them in the caller. eg:

$ cat assign
POSTGRES_USER=dbuser
POSTGRES_PASS=dbpasswd
POSTGRES_DBNAME=db
POSTGRES_HOST=123.123.123.123
POSTGRES_PORT=5432
$ cat script_without_export 
#!/usr/bin/env bash
. assign
./assign_db_url
$ cat script_with_export 
#!/usr/bin/env bash
. assign
export POSTGRES_USER POSTGRES_PASS POSTGRES_DBNAME POSTGRES_HOST POSTGRES_PORT
./assign_db_url
$ cat assign_db_url 
#!/usr/bin/env bash
DATABASE_URL="postgres://${POSTGRES_USER?}:$POSTGRES_PASS@$POSTGRES_HOST:$POSTGRES_PORT/$POSTGRES_DBNAME"
echo DATABASE_URL=$DATABASE_URL

$ ./script_with_export 
DATABASE_URL=postgres://dbuser:dbpasswd@123.123.123.123:5432/db
$ ./script_without_export 
./assign_db_url: line 2: POSTGRES_USER: parameter null or not set

Note the usage of the defensive ${arg?} here. A very useful, but oft overlooked construction which aborts the script if arg is not set. (Compare to ${arg:?} which aborts if arg is unset or if it is the empty string.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading