How to list variables declared in script in bash?

后端 未结 14 979
走了就别回头了
走了就别回头了 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:34

    for i in _ {a..z} {A..Z}; do eval "echo \${!$i@}" ; done | xargs printf "%s\n"
    

    This must print all shell variables names. You can get a list before and after sourcing your file just like with "set" to diff which variables are new (as explained in the other answers). But keep in mind such filtering with diff can filter out some variables that you need but were present before sourcing your file.

    In your case, if you know your variables' names start with "VARIABLE", then you can source your script and do:

    for var in ${!VARIABLE@}; do
       printf "%s%q\n" "$var=" "${!var}"
    done
    

    UPDATE: For pure BASH solution (no external commands used):

    for i in _ {a..z} {A..Z}; do
       for var in `eval echo "\\${!$i@}"`; do
          echo $var
          # you can test if $var matches some criteria and put it in the file or ignore
       done 
    done
    

提交回复
热议问题