2

I know it is common to use catch when executing commands that may return non-zero... but how can I get the output in that case?

To be specific, I wish to do something like "catch {exec diff fileA fileB} ret". The files are different and ret value is 1. What I actaully need is the output of diff, the detailed differences. But I believe the "catch {exec ...} err" practice does not provide it, right?

Can someone please suggest on this task? Is there tcl-builtin commands to do file diff? (I think it is possible to redirect the output to a file and then read the file... are there any other alternatives?)

Thanks! XM

X.M.
  • 941
  • 3
  • 14
  • 22
  • PS: in case of not using 'catch' for the 'exec', it returns with 'child process exited abnormally' after execution, which prevents the program to continue, that's why I am 'bound' to work with catch, but if you are able to get rid of it, that would be great and acceptable. – X.M. Jul 19 '10 at 03:01
  • I consider the "canonical" usage of catch with exec to be here: KBK's contribution to http://wiki.tcl.tk/exec – glenn jackman Jul 19 '10 at 13:27
  • I have read wiki.tcl.tk and added it to my favorite list. Thanks Glenn! – X.M. Jul 20 '10 at 01:28

1 Answers1

5

From a recent project of mine:

set status [catch {exec diff $file1 $file2} result]
if {$status == 0} {
   puts "$file1 and $file2 are identical"
} elseif {$status == 1} {
   puts "** $file1 and $file2 are different **"
   puts "***************************************************************************"
   puts ""
   puts $result
   puts ""
   puts "***************************************************************************"
} else {
   puts stderr "** diff exited with status $status **"
   puts stderr "***********************************************************************"
   puts stderr $result
   puts stderr "***********************************************************************"
}

Bottom line, when the files are different, the status is 1 and $result holds the diff output. At the end of the diff output I do get the "child process exited abnormally". In my case I have not remove it, but it should be easy enough to do.

Andrew Stein
  • 12,880
  • 5
  • 35
  • 43
  • Thank you Andrew... I did almost the same as yours but I was not careful to check $result; it has what I needed :) By the way, your code will get something like 'result: couldn't execute "diff -rwsq fileA.tcl fileB.tcl', so I used command [catch {exec sh -c $cmd} result] and 'couldn't execute' is gone. Thanks! – X.M. Jul 19 '10 at 05:30