Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop not working in shell script while running the script from crontab

I am trying to read a file line by line using while loop like:

while read Line; do
     echo Inside outer loop
     while read Line2; do
          .....
          echo Inside inner loop
          .....
     done < /absolute path of file/filename2
done < /absolute path of file/filename

The script is working fine when running standalone. But it does not go inside loop when it gets run from crontab.

Please suggest what could be the possible reason of it.

like image 241
Akhil Tiwari Avatar asked Dec 28 '25 02:12

Akhil Tiwari


1 Answers

The 2nd while loop is reading all the input (except for the first line of "filename"). You need to redirect to separate file descriptors:

while IFS= read -r -u3 Line; do
     echo Inside outer loop
     while IFS= read -r -u4 Line2; do
          .....
          echo Inside inner loop
          .....
     done 4< "/absolute path of file/filename2"
done 3< "/absolute path of file/filename"
  • Using IFS= and read -r to ensure the line is read verbatim from the file.
  • read -u3 and 3< file to use a specific fd
  • if your real paths have space, you need to quote the filename
like image 179
glenn jackman Avatar answered Dec 30 '25 22:12

glenn jackman