繁体   English   中英

如何从文件集合中仅选择shell脚本

[英]how do I select only shell scripts from a collection of files

我想找到我所有的bash脚本(我现在已经积累了很多)并自动通过bash -n运行它们。

什么是快速的方法呢? 我想让grep只匹配第一个非空白行以#!/bin/sh#!/usr/bin/env sh#!/usr/bin/env bash#!/bin/bash开头的文件#!/bin/bash ......

一个可用的答案当然是有用的

for file in *; do 
    if head -n 5 $file | grep "#!.*sh$" > /dev/null; then
        bash -n $file
    fi
done

但是为了“正确”,我怎么能合理地只在第一个非空白(或非空白)线上做我的grep?

使用find:

     find . -type f -exec grep -e "^#\!\/bin\/.*sh$" {} +

GNU awk

awk '
FNR==1 && $0~/#!\/bin\/sh|#!\/usr\/bin\/env sh|#!\/usr\/bin\/env bash|#!\/bin\/bash/ { 
    print FILENAME " is shell script";
}
FNR>1 {
    nextfile
}' *
  • 你可以使用上面的regex并将它减少到#!
  • FNR==1以及regex将确保检查第一行的she-bang线。
  • nextfile将确保没有文件超出第一行。
  • print如果只是为了记录。
  • FILENAME将打印正在检查的文件的名称。
  • *将glob到工作目录下的所有文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM