简体   繁体   English

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

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

I want to find all my bash scripts (i have accumulated many of them now) and run them all through bash -n automatically. 我想找到我所有的bash脚本(我现在已经积累了很多)并自动通过bash -n运行它们。

What's a quick way to do this? 什么是快速的方法呢? I'd like to have grep match only the files whose first non blank lines start with #!/bin/sh or #!/usr/bin/env sh or #!/usr/bin/env bash or #!/bin/bash ... 我想让grep只匹配第一个非空白行以#!/bin/sh#!/usr/bin/env sh#!/usr/bin/env bash#!/bin/bash开头的文件#!/bin/bash ......

A serviceable answer is of course something along the lines of 一个可用的答案当然是有用的

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

But for the sake of "correctness" how might I reasonably do my grep on only the first non-whitespace (or alternatively non-blank) line? 但是为了“正确”,我怎么能合理地只在第一个非空白(或非空白)线上做我的grep?

使用find:

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

With GNU awk 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
}' *
  • You can play around with the above regex and reduce it to just #! 你可以使用上面的regex并将它减少到#! .
  • FNR==1 along with the regex would ensure that the first line is checked for she-bang line. FNR==1以及regex将确保检查第一行的she-bang线。
  • nextfile would ensure that no file is looked beyond first line. nextfile将确保没有文件超出第一行。
  • print if just for logging. print如果只是为了记录。
  • FILENAME will print the name of the file under inspection. FILENAME将打印正在检查的文件的名称。
  • * will glob to all files under working directory. *将glob到工作目录下的所有文件。

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

相关问题 如何使用Shell将字符串添加到另一个目录中文件集合名称的开头 - How do I add a string to the beginning of the name of a collection of files in another directory using shell 如何将 Jenkins 参数作为 arguments 传递给从作业 DSL 中的文件读取的 shell 脚本? - How do I pass Jenkins parameters as arguments to a shell scripts read from file in Job DSL? 如何使用Vim中的代码折叠来运行shell脚本 - How do I get Code Folding in Vim for shell scripts working 如何在cygwin中运行bash shell脚本? - How do I run bash shell scripts in cygwin? 如何使用Shell脚本提取xml属性? - How do I extract xml properties using shell scripts? 如何仅在 Bash shell 的当前目录中仅打印包含字符串的文件? - How do I print only files that contain the string only in my current directory in Bash shell? 从文件列表中并行运行 shell 个脚本 - Running shell scripts in parallel from a list of files 我需要远离大文件的bash脚本吗? - Do I need stay away from bash scripts for big files? 如何在shell脚本中创建别名? - How do create an alias in shell scripts? 如何从一个目录中读取文件并使用shell脚本将该文件作为另一个存储过程的输入? - How to read the files from one directory and give the file as input of another stored procedure using shell scripts?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM