How to iterate through all the ENV variables printing key and value?

前端 未结 2 745
时光说笑
时光说笑 2021-01-12 01:55

I\'d like to iterate through the variables in env printing:

name: ${name} value: ${value}

Simply splitting by line break and iterating does

相关标签:
2条回答
  • 2021-01-12 02:13

    Here's the solution from #bash.

    unset IFS
    args=() i=0
    for var in $(compgen -e); do
        printf -v 'args[i++]' -e%s=%s "$var" "${!var}"
    done
    

    I initially thought the idea was to output, hence printf %q was necessary, but that's not the case when just building an arguments array, so it can be simplified to this:

    unset IFS
    args=()
    for var in $(compgen -e); do
        args+=( "-e$var=${!var}" )
    done
    
    0 讨论(0)
  • 2021-01-12 02:33

    You can use env -0 to get a null terminated list of name=value pairs and use a for loop to iterate:

    while IFS='=' read -r -d '' n v; do
        printf "'%s'='%s'\n" "$n" "$v"
    done < <(env -0)
    

    Above script use process substitution, which is a BASH feature. On older shells you can use a pipeline:

    env -0 | while IFS='=' read -r -d '' n v; do
        printf "'%s'='%s'\n" "$n" "$v"
    done
    
    0 讨论(0)
提交回复
热议问题