• Uncategorized

About linux : Execute-function-for-every-subfolder

Question Detail

I have a folder named students_projects that contains 10 subfolders. Each subfolder has project1.c and project2.c, each one prints a value. I made a bash script function that check those numbers and save them to a txt file. I tested it with 2 .c files named project1 and project2 in Desktop and not in the folder. I made sure that i worked fine but when i went to run it for all the subfolders it keeps saving the values that are in desktop files.

My function:

function test () {
  gcc project1.c
  p1=$(./a.out)
  if (( $p1 == 20 ));
  then
    v1=30
  else
    v1=0
  fi
  gcc project2.c
  p2=$(./a.out)
  if (($p2 == 10 ));
  then
    v2=70
  else
    v2=0
  fi
  sum=$(( $v1 + $v2 ))
  on="cut -d' ' -f1 report.txt"
  onoma=$(eval "$on")
  temp="cut -d' ' -f2 report.txt"
  am=$(eval "$temp")
  printf "$onoma $am project1: $v1 project2: $v2 total_grade: $sum\n" >> grades.txt
}

Then i do

for FILE in students_projects/* ; do
  test
done

Question Answer

Looks like the grades.txt file is at the top level, but you want to run test under each directory. The easiest change is to pass a full path to $PWD/grades.txt to the function. Coombine that with running “cd” into each subdir. Recommendation:

for FILE in students_projects/* ; do
  (cd $FILE; test $PWD/grades.txt)
done

Then in your “function test()”, use that $1 argument instead of grades.txt:

printf "..." >> $1

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.