Home > front end >  how to print environment variable value in shell of a variable whose name is present in another vari
how to print environment variable value in shell of a variable whose name is present in another vari

Time:09-17

I have store environment variable names in an array with name array and I want to check if it is set then only certain code should run. Like if somebody has set environment variable db_instance_type="t2.micro" then desire output should be -var="db_instance_type=$db_instance_type"

I have written below code but it is not working as expected because I am checking variable presence using single $ which will always be there and not checking main variable value.

set -u
db_instance_type="t2.micro" # for testing only
db_dns_ttl="300"    # for testing only
function check_input_vars() {
    local temp_cmd=''

    declare -a array=(db_instance_type db_vpc_id db_subnet_ids db_sg_cidr_allowed_range db_ebs_volume_size delete_on_termination_db_ebs_volume
                    security_group_id contact db_image_owner_id db_dns_ttl db_image_name_filter ws_key_name ws_dns_ttl ws_instance_type
                    ws_vpc_id  ws_subnet_ids ws_ami_id enable_ws_public_ip
                    )

    temp_cmd=''
    for var in "${array[@]}"
    do
        var_name=(${!var@})
        if [[ "${var_name}" ]]; then 
            temp_cmd =" -var=\"$var=\$$var\""
        fi
    done   
    echo $temp_cmd
}

input_var_str="$(check_input_vars)"
echo "$input_var_str"  # output should be: -var="db_instance_type=$db_instance_type" -var="db_dns_ttl=$db_dns_ttl
unset db_instance_type  # for testing only

Fix:

I have to comment this line --> #set -u And I have used below code:

var_value=${!var}
if [[ ! -z "${var_value}" ]]; then temp_cmd =" -var=\"$var=\$$var\""; fi

CodePudding user response:

The syntax is off - to get the variable value use ${!var}. No @. And ( ) are for array assignment - it's not an array, it's a single vlaue.

    var_value=${!var}
    if [[ -n "${var_value}" ]]; then..

Also, it accesses the value of the variable, where variable var stores the name of the variable, thus I would call the variable var_value.

Check your scripts with https://shellcheck.net .

To protect against set -u, expand variable to empty when not defined or empty.

 var_value=${!var:-}

Also: How to check if a variable is set in Bash?


output should be: -var="db_instance_type=$db_instance_type" -var="db_dns_ttl=$db_dns_ttl"

Related reading: https://mywiki.wooledge.org/BashFAQ/048 https://mywiki.wooledge.org/BashFAQ/050 https://mywiki.wooledge.org/BashFAQ/006 .

  • Related