arrays - bash loop to assign variables values without overwriting previously declared variables -


the setup have declare several variables in config file , run processes depend on variables. additional functionality i'm trying provide default_variables script give default values variables in config files, while not overriding declared in config file.

here current code:

#!/bin/bash -x  # allows var used associative array declare -a var  # variable declarations must of form: # var[var_name]=var_value # after processing loop, above evaluated as: # export var_name=var_value  # declare default variables var[a]=a_val var[b]=b_val var[c]=c_val var[d]=d_val  # iterate on associative array indices default_var in `echo "${!var[@]}"`  test_var=\$${default_var}    # export variables have not been declared   if [[ -z `eval $test_var` ]]        # export each index name variable     export $default_var=${var[$default_var]}   fi done 

the error i'm getting eval statement tries execute value of variable if declared before script ran. instance, if above script ran twice error be:

-sh: a_val: command not found -sh: b_val: command not found -sh: c_val: command not found -sh: d_val: command not found 

now more elegant way of solving problem, best come with. finally, know exporting values , checking each variable individually see if allocated more "correct" way of doing this, don't want exponentially bloat script , don't want people have copy logic every time want add new variable script , can't run default_variables script before config file allowing override default values because default values depend on config values.

thanks in advance help!

don't use eval, causes argument executed command. want value of variable named $default_var. there syntax indirect variable reference:

if [[ -z ${!default_var} ]] 

although wanted test non-empty. -z tests empty. should be.

if [[ -n ${!default_var} ]] 

also, overcomplicated, , arguably incorrect:

for default_var in `echo "${!var[@]}"` 

just write:

for default_var in "${!var[@]}" 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -