2

I would like to check for (only) python files for those which do not have the #!/usr/bin/env python in the first line. So, I write a bash script that does the following:

#!/bin/bash

#list all of python files

for file in `find . -name "*.py"`
do
        if [ `head -1 $file` != "#!/usr/bin/env python"] then;
                 echo "no match in file $file"
        else then;
                 echo "match!"
        fi
done

However, for some reason I cannot get the if statement correct! I've looked at many questions, but I cannot find one that succinctly describes the issue. Here is the error message:

./run_test.sh: line 9: syntax error near unexpected token `else'
./run_test.sh: line 9: `    else then;'

where am I going awry? Thank you.

Cyphase
  • 11,502
  • 2
  • 31
  • 32
makansij
  • 9,303
  • 37
  • 105
  • 183

3 Answers3

2

You can do something like

find . -type f -name '*.py' -exec \
  awk 'NR==1 && /#!\/usr\/bin\/env python/ \
  { print "Match in file " FILENAME; exit } \
  { print "No match in file " FILENAME; exit }' \
{} \;

If you are going to loop over it, don't use a for loop

#!/bin/bash
find . -type f -name '*.py' -print0 | while IFS= read -r -d $'\0' file; do
  if [[ $(head -n1 "$file") == "#!/usr/bin/env python" ]]; then
      echo "Match in file [$file]"
  else
      echo "No match in file [$file]"
  fi
done
Community
  • 1
  • 1
Reinstate Monica Please
  • 11,123
  • 3
  • 27
  • 48
1

Things to notice:

  1. The [] after your if statement needs correct spacing
  2. The ';' (if you enter a new line is not necessary) goes after the if and not after the then
  3. You added an extra then after the else.

    #!/bin/bash
    
    #list all of python files
    
    for file in `find . -name "*.py"` 
    do
         if [ `head -1 $file` != "#!/usr/bin/env python" ]; 
         then
             echo "no match in file $file"
         else 
             echo "match!"
         fi
    done
    
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
-1

can you use -exec option by any chance? I find it easier.

find . -name "*.py" -exec head -1 {} | grep -H '#!/usr/bin/env python' \;

You can control the output using grep options.


edit

Thanks to @chepner - To avoid the pipe being swallowed too early:

-exec sh -c "head -1 {} | grep -H '#!/usr/bin/env python'" \;
Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58