Command output redirection to file issues

Hi,

I have a peculiar issue w.r.t redirecting the command output to a file when using loop.

I am redirecting command output to same file in a series of if condition statements, but if one block of if condition statement writes the log to the file , the subsequent block of if condition satisfied command outputs not logged to the output file.

Second If condition statement will begin after completion of first if...fi block only.

Well, looking into my personal and reliable crystal bowl after a careful and painstaking polish, I can see the answer: "Correct the subsequent block's output redirection!"

OK, let's become serious:

Please become accustomed to provide decent context info of your problem.
It is always helpful to support a request with system info like OS and shell, related environment (variables, options), preferred tools, and adequate (representative) sample input and desired output data and the logics connecting the two, to avoid ambiguities and keep people from guessing.

Can you share your code so we can actually see it? If it is huge, then please post a meaningful skeleton that exhibits the same issue so we can consider it and help you find a solution.

Please post the code wrapped in CODE tags for clarity.

Kind regards,
Robin

Hi

If I change the file name in the second part it is writing in to that file, but if both files are same only problem occurs.

Finally found the issues. I was initializing the file content in the start of the for loop with > and appending to it in the subsequent if loops >>

So for scenarios where nothing to write in the file for the for loop it simply overwrites the existing file while initializing.

Solved

Thanks for explaining.

We wouldn't have been able to guess that without seeing it.

You could also replace code like this:-

for file in *
do
   if [ "$file" = "File_A" ]
   then
      echo "Found A" >> logfile.txt
   fi
   if [ "$file" = "File_B" ]
   then
      echo "Found B" >> logfile.txt
   fi
   if [ "$file" = "File_C" ]
   then
      echo "Found C" >> logfile.txt
   fi
done

.... with something like this:-

for file in *
do
   if [ "$file" = "File_A" ]
   then
      echo "Found A"
   fi
   if [ "$file" = "File_B" ]
   then
      echo "Found B"
   fi
   if [ "$file" = "File_C" ]
   then
      echo "Found C"
   fi
done > logfile.txt 2> logfiles.err

It's terrible dummy code, I know, but it has one output redirection and all STDOUT from the loop goes to it.

Does that give you something to work with to smarten your code?

Robin