bash

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?


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.)