Search code examples
bashshelltee

tee command not working


I am running a script which is using tee command to log the output to screen and also to a file. Script is as follows:

Script.sh:
count=1
while [ $count -le 10 ]
do
  echo "`date` : Function call, loopcount - $count" | tee -a logfile.log
  functioncall
  count=$( $count + 1 )
done

The fucntioncall() function is defined in the same script.

functioncall(){

<some processing>
cd $Location
<some processing>
}

When I run Script.sh, this script runs successfully, but only one entry is made in the logfile.log, for the first run, whereas in the output screen I can see that the loop is running for 10 times with correct loopcount incremented and displayed, but the entry in the logfile.log is not done.

When I comment line cd $Location in the script it behaves as desired, means both O/P and logfile.log show the correct loopcount.

Any idea why this undefined behavior is observed? Any fix/workaround is greatly appreciated!


Solution

  • When you change directory it is changed. Which means that tee will write to a new file.

    Possible solutions:

    • instead of tee -a logfile.log use tee -a <absolute_path_to_current_directory>/logfile.log
    • move the whole tee outside the loop:

      while
      do
          stuff
      done | tee logfile.log # bonus - you don't need -a here
      
    • return to initial location after cd. Which should be actually done with pushd and popd

    • do not do cd in main shell. Do all processing in subshell:

      (cd $location;
          <some processing>)
      

    I myself prefer the last one.

    On the other hand (and that might be even better) - rewrite the processing to avoid cd at all.