How to list variables declared in script in bash?

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

    If you're only concerned with printing a list of variables with static values (i.e. expansion doesn't work in this case) then another option would be to add start and end markers to your file that tell you where your block of static variable definitions is, e.g.

    #!/bin/bash
    
    # some code
    
    # region variables
    VAR1=FOO
    VAR2=BAR
    # endregion
    
    # more code
    

    Then you can just print that part of the file.

    Here's something I whipped up for that:

    function show_configuration() {
       local START_LINE=$(( $(< "$0" grep -m 1 -n "region variables" | cut -d: -f1) + 1 ))
       local END_LINE=$(( $(< "$0" grep -m 1 -n "endregion" | cut -d: -f1) - 1 ))
       < "$0" awk "${START_LINE} <= NR && NR <= ${END_LINE}"
    }
    
    

    First, note that the block of variables resides in the same file this function is in, so I can use $0 to access the contents of the file.

    I use "region" markers to separate different regions of code. So I simply grep for the "variable" region marker (first match: grep -m 1) and let grep prefix the line number (grep -n). Then I have to cut the line number from the match output (splitting on :). Lastly, add or subtract 1 because I don't want the markers to be part of the output.

    Now, to print that range of the file I use awk with line number conditions.

提交回复
热议问题