Executing UNIX Commands

Most UNIX commands can be executed by calling exec. The arguments generally follow the /bin/sh conventions including ">“, "<“, "|“, "&“, and variations on them. Use whitespace before and after the redirection symbols.

tclsh> exec date
Thu Feb 24  9:32:00 EST 1994
tclsh> exec date | wc -w
       6
tclsh> exec date > /tmp/foo
tclsh> exec cat /tmp/foo
Thu Feb 24  9:32:03 EST 1994

Unless redirected, the standard output of the exec command is returned as the result. This enables you to save the output of a program in a variable or use it in another command.

tclsh> puts "The date is [exec date]"
The date is Thu Feb 24  9:32:17 EST 1994

Tcl assumes that UNIX programs return the exit value 0 if successful. Use catch to test whether a program succeeds or not. The following command returns the exit value from mv which could, for example, indicate that a file did not exist.

catch {exec mv oldname newname}

Many programs return nonzero exit values even if they were successful. For example, diff returns an exit value of 1 when it finds that two files are different. Some UNIX programs are sloppy and return a random exit value which can generate an error in exec. An error is also generated if a programs writes to its standard error stream. It is common to use catch with exec to deal with these problems.

Tilde substitution is performed on the command but not on the arguments, and no globbing is done at all. So if you want to delete all the .o files in a directory, for instance, it must be ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.