Bash 如何使用awk、sed或grep检查源代码中的全局变量?

Bash 如何使用awk、sed或grep检查源代码中的全局变量?,bash,shell,awk,sed,grep,Bash,Shell,Awk,Sed,Grep,我需要针对包含逻辑的bash脚本运行一系列Python源代码,以检查是否存在全局变量。我可以使用两个标准来确定变量是否为全局变量: read file line by line if there is an '=' (assignment sign) in the line AND no '#' in beginning of line (it is not commented out), check: is there a 'def' string anywhere in the te

我需要针对包含逻辑的bash脚本运行一系列
Python
源代码,以检查是否存在全局变量。我可以使用两个标准来确定变量是否为全局变量:

read file line by line
if there is an '=' (assignment sign) in the line AND no '#' in beginning of line (it is not commented out), check:
    is there a 'def' string anywhere in the text above this assignment line, e.g. def function_name()?
         if yes, variable within a function and hence not global
         else, possible global variable
如何使用
grep
awk
sed
实现此伪代码?我也愿意接受关于使用bash脚本查找全局变量的更好策略的建议

示例代码:

int a = 23

def func_name():
    ...body...
这个代码没有通过我们的测试

示例代码2:

def function_name():
    int a = 4
    ...

这段代码通过了测试。

我认为这不是一个好主意,但下面是您的逻辑的文字实现:

awk-F='1〕
/^[^#]/&&NF>1&&saw_def{print“not global:”,$0;next}
NF>1{print“可能是全局的:,$0}
{saw_def=/def/}
'file.py
这告诉awk在四个
模式{action}
对上使用
=
作为字段分隔符:

  • 行以非
    #
    开头,有第二个字段(因此有一个
    =
    ),并设置
    saw_def
    变量:
    将行打印为非全局赋值;转到下一行(停止模式匹配)
  • 否则,该行有一个
    =

    将该行打印为可能的全局赋值
  • (与#1不匹配的任何行):
    saw_def
    设置为表示行上是否存在“def”的布尔值
  • 以下是一个测试失败的示例:

    def function_name():
    INTA=4
    int b=8
    
    您请求的逻辑将注意到
    a
    不是全局的,
    b
    可能是全局的


    这应该更好:

    awk '
      NF == 0 { next }
      {
        indent = match ($0, /[^ \t]/) - 1  # count of leading whitespace
        has_assign = /^[^#]*=/
      }
      $1 == "def" && !in_def { in_def = indent; next }
      indent > in_def && has_assign { print "not global:", $0; next }
      indent <= in_def { in_def = 0 }
      has_assign { print "possibly global:", $0 }
    ' file.py
    
    awk'
    NF==0{next}
    {
    缩进=匹配($0,/[^\t]/)-1#前导空格计数
    has_assign=/^[^#]*=/
    }
    $1==“def”&&!in_def{in_def=indent;next}
    缩进>在def和has中分配{print“not global:,$0;next}
    
    indent添加了两个示例,使问题更加具体。当有好的Python源代码分析器用Python编写时,使用面向行的工具分析Python源代码似乎是非常错误的。如前所述,实现此伪代码的可能重复之处很小:您需要一个触发器,它最初是错误的,遇到
    def
    时设置为true,遇到函数结束时再次设置为false。每当你看到一个<代码>=<代码>,触发器是错误的,你就把它当作全局变量。当然,真正的问题已经在伪代码中:它偶尔会报告一个正确的全局,但也会给出错误的正误,并且会错过一些全局变量。如果不使用Python,考虑这种类型的事情是很有意思的。但如果您在实际安装了python的系统上解析已知的安全python代码,那么这也是不明智的。如果您不想运行代码(可能是在网上找到的?)和/或没有在本地安装python,这可能是一个有趣的前提。看看我的答案。