How to list variables declared in script in bash?

后端 未结 14 1021
走了就别回头了
走了就别回头了 2020-11-28 20:03

In my script in bash, there are lot of variables, and I have to make something to save them to file. My question is how to list all variables declared in my script and get l

14条回答
  •  不思量自难忘°
    2020-11-28 20:15

    If you can post-process, (as already mentioned) you might just place a set call at the beginning and end of your script (each to a different file) and do a diff on the two files. Realize that this will still contain some noise.

    You can also do this programatically. To limit the output to just your current scope, you would have to implement a wrapper to variable creation. For example

    store() {
        export ${1}="${*:2}"
        [[ ${STORED} =~ "(^| )${1}($| )" ]] || STORED="${STORED} ${1}"
    }
    
    store VAR1 abc
    store VAR2 bcd
    store VAR3 cde
    
    for i in ${STORED}; do
        echo "${i}=${!i}"
    done
    

    Which yields

    VAR1=abc
    VAR2=bcd
    VAR3=cde
    

提交回复
热议问题