Redirection question

I want to redirect stderr and have the following peice of code

 
$ cat t1.ksh
#!/bin/ksh
func2()
{
  diff /tmp/jdlkwjdlkejew /tmp/djlkwejdlewdjew >$OUTPUT_FILE 2>>$ERR_FILE
}

func1()
{
  let counter=0
  while [ $counter -lt 5 ]
  do
   print -u2 "Error: In main function"
   func2
   let counter=$counter+1
  done

} >$OUTPUT_FILE 2>$ERR_FILE

OUTPUT_FILE=/tmp/junk.out
ERR_FILE=/tmp/junk.err
rm -rf $OUTPUT_FILE $ERR_FILE
func1

When I run the code this is what my junk.err contains

 
$ cat junk.err
Error: In main function
Error: In main function
Error: In main function
Error: In main function
Error: In main function
rectory
diff: /tmp/jdlkwjdlkejew: No such file or directory
diff: /tmp/jdlkwjdlkejew: No such file or directory
diff: /tmp/jdlkwjdlkejew: No such file or directory

How can I make my errors appear in the correct order

 
Error: In main function
diff: /tmp/jdlkwjdlkejew: No such file or directory
Error: In main function
diff: /tmp/jdlkwjdlkejew: No such file or directory
...
...

Secondly, it looks like I got part of an erorr. I need to redirect the
func1 as shown because that is a standard template but I need to
capture errors from other functions. Can somebody show me how
to fix this issue

You could remove the redirect inside func2:

zsh-4.3.11[t]% cat t1.ksh 
#!/bin/ksh
func2()
{
  diff /tmp/jdlkwjdlkejew /tmp/djlkwejdlewdjew
}

func1()
{
  let counter=0
  while [ $counter -lt 5 ]
  do
   print -u2 "Error: In main function"
   func2
   let counter=$counter+1
  done

} >$OUTPUT_FILE 2>$ERR_FILE

OUTPUT_FILE=/tmp/junk.out
ERR_FILE=/tmp/junk.err
rm -rf $OUTPUT_FILE $ERR_FILE
func1
zsh-4.3.11[t]% ./t1.ksh 
zsh-4.3.11[t]% cat /tmp/junk.err 
Error: In main function
diff: /tmp/jdlkwjdlkejew: No such file or directory
diff: /tmp/djlkwejdlewdjew: No such file or directory
Error: In main function
diff: /tmp/jdlkwjdlkejew: No such file or directory
diff: /tmp/djlkwejdlewdjew: No such file or directory
Error: In main function
diff: /tmp/jdlkwjdlkejew: No such file or directory
diff: /tmp/djlkwejdlewdjew: No such file or directory
Error: In main function
diff: /tmp/jdlkwjdlkejew: No such file or directory
diff: /tmp/djlkwejdlewdjew: No such file or directory
Error: In main function
diff: /tmp/jdlkwjdlkejew: No such file or directory
diff: /tmp/djlkwejdlewdjew: No such file or directory
zsh-4.3.11[t]% 
1 Like