【问题标题】:Validate .sh files header验证 .sh 文件头
【发布时间】:2021-03-11 15:20:54
【问题描述】:

如何验证以 .sh 结尾的指定目录中的每个 .sh 文件,以确保第一行是 #!/bin/bash?

我希望每个文件的输出为 filename.sh is validfilename.sh is missing the header

【问题讨论】:

    标签: linux bash shell sh linux-mint


    【解决方案1】:

    可能是这样的

    awk 'FNR == 1 { if ($0 == "#!/bin/bash") {
                       print FILENAME, "is valid"
                    } else {
                       print FILENAME, "is missing the header"
                    }
                    nextfile
         }' *.sh
    

    【讨论】:

      【解决方案2】:

      还可以考虑纯 bash 解决方案。它不调用任何其他进程。

      请注意,有效文件可能在#!/bin/bash 之间包含空格。

      #! /bin/bash
      PAT="^#! */bin/bash"
      for file in *.sh ; do
          line=
          read line < $file
          if [[ "$line" =~ $PAT ]] ; then
              echo "$file is valid"
          else
              echo "$file is missing the header"
          fi
      done
      

      如果您需要支持其他解释器(例如 bin/sh),您可以扩展该模式以包含其他 shell

      PAT="#! *(/bin/bash|/bin/sh)"
      

      【讨论】:

      • 感谢您的帮助
      猜你喜欢
      • 2015-05-02
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2012-05-22
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多