Search code examples
awk

How do I use environment variables in Awk


I've got the following AWK script I'm using to update settings.py. I utilising during Docker install and I'm trying to pass ENV variables.

ENV variables to pass:

DB_USER,
DB_PASS,
DB_NAME

The code below

awk 'function pr(sp, k, v){    # prints key-value pair with indentation
         printf "%s\047%s\047: \047%s\047,\n",sp,k,v; 
     }
     /sqlite/{ sub(/sqlite[0-9]*/,"mysql",$0) }
     /NAME/{ sp=substr($0,1,index($0,"\047")-1); 
             print sp$1" \047$DB_NAME\047"; 
             pr(sp,"USER","$DB_USER"); pr(sp,"PASSWORD","$DB_PASS"); 
             pr(sp,"HOST","localhost"); pr(sp,"PORT",""); next 
     }1'

Solution

  • You can use the ENVIRON variable in GNU Awk,

    From the GNU Awk man page,

    ENVIRON

    An associative array containing the values of the environment. The array indices are the environment variable names; the elements are the values of the particular environment variables. For example, ENVIRON["HOME"] might be "/home/arnold". Changing this array does not affect the environment passed on to any programs that awk may spawn via redirection or the system() function. (In a future version of gawk, it may do so.)

    Using the above array to reference your environment variables, just do this in the BEGIN clause to load all the variables and use it later

    awk 'BEGIN {
        db_user = ENVIRON["DB_USER"]
        db_pass = ENVIRON["DB_PASS"]
        db_name = ENVIRON["DB_NAME"]
     }'
    

    Use the variables db_user, db_pass and db_name in the body of the Awk as you wish. By importing the environment variables in BEGIN, you don't have to import them once for each line in the input file.