How to select only shell scripts from a collection of files

I want to find all my bash scripts (I have accumulated a lot of them now) and automatically run them through bash -n .

What is a quick way to do this? I would like grep match only files whose first non-empty lines start with #!/bin/sh or #!/usr/bin/env sh or #!/usr/bin/env bash or #!/bin/bash . ..

The correct answer is, of course, something like

 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 can I reasonably make my grep on only the first line without spaces (or, alternatively, not empty) ?

+4
source share
2 answers

Using find:

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

With 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 with the regex above and reduce it to #! .
  • FNR==1 along with regex ensures that the first line is checked for the she-bang .
  • nextfile ensures that the file will not be viewed outside the first line.
  • print , if only for logging.
  • FILENAME print the name of the file to be scanned.
  • * will be glob for all files in the working directory.
+2
source

Source: https://habr.com/ru/post/1485135/


All Articles