Parameter expansion in bash for loop to retreive key and value

Viewed 28

I'm not sure what is doing this for loop in Bash that is using this kind of parameter expansions var_key="${env%%=*}"

    for env in "${envvars[@]}"; do
        var_key="${env%%=*}"
        var_value="${env#*=}"
        if [[ -z ${!var_key} ]]; then
            echo "export ${env}" >> "${FILE}"
            echo "export ${var_key}=\"${var_value}\"" >> "${FILE}"
        fi
    done

Any idea of what is being doing this for loop.

1 Answers

"${env%%=*}" is one possible form of a "parameter expansion". It removes the longest match of the pattern =* from the value of the variable $env. # is similar but operates on the beginning of the value.

E.g.

env=x=3=6
echo ${env%%=*}  # x
echo ${env%=*}   # x=3
echo ${env#*=})  # 3=6
echo ${env##*=}) # 6
Related