Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mistake in for loop

When I run my script I get this error:

234.sh: line 3: syntax error near unexpected token `do
234.sh: line 3: `for folder in $array ; do

I don't see the mistake. Help?

#!/bin/bash
base=$(pwd)
array=`find * -type d`
 for folder in $array ; do
  cd $folder ;
  grep -n $1 * | while read line ;
   do    name=$(echo "$line" | cut -f1 -d:) ;
        if [ "$name" == "1234.sh" ]; then
        continue ;
        else
        string=$(echo "$line" | cut -f2 -d:) ;
        a=$(expr $string - 10)
        if [ $a -lt 1 ] ; then 
        a=1 ;
        fi ;
        b=$(expr $string + 10) ;   
        echo "-----------------------"
        echo $name:$a
        sed -n $a,${b}p $name;
        fi ;
    done
   cd $base ;
done
like image 669
Masha Misery Avatar asked Mar 27 '26 23:03

Masha Misery


1 Answers

A few suggestions:

  1. Make array a proper array, not just a string. (This is the only suggestion that actually addresses your syntax error.)

  2. Quote parameters

  3. Use IFS to allow read to split your line into its two components

  4. Use a subshell to eliminate the need to cd $base.

  5. Most of your semicolons are unnecessary.


#!/bin/bash
array=( `find * -type d` )
for folder in "${array[@]}" ; do
  ( cd $folder
    grep -n "$1" * | while IFS=: read fname count match; do
      [ "$fname" == "1234.sh" ] && continue

      a=$(expr $count - 10); [ $a -lt 1 ] && a=1
      b=$(expr $count + 10) 
      echo "-----------------------"
      echo $fname:$a
      sed -n $a,${b}p $fname
    done
  )
done
like image 133
chepner Avatar answered Mar 29 '26 21:03

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!