1exec(n) Tcl Built-In Commands exec(n)
2
3
4
5______________________________________________________________________________
6
8 exec - Invoke subprocesses
9
11 exec ?switches? arg ?arg ...? ?&?
12______________________________________________________________________________
13
15 This command treats its arguments as the specification of one or more
16 subprocesses to execute. The arguments take the form of a standard
17 shell pipeline where each arg becomes one word of a command, and each
18 distinct command becomes a subprocess. The result of the command is
19 the standard output of the final subprocess in the pipeline, inter‐
20 preted using the system encoding; to use any other encoding (especially
21 including binary data), the pipeline must be opened, configured and
22 read explicitly.
23
24 If the initial arguments to exec start with - then they are treated as
25 command-line switches and are not part of the pipeline specification.
26 The following switches are currently supported:
27
28 -ignorestderr
29 Stops the exec command from treating the output of mes‐
30 sages to the pipeline's standard error channel as an error
31 case.
32
33 -keepnewline Retains a trailing newline in the pipeline's output. Nor‐
34 mally a trailing newline will be deleted.
35
36 -- Marks the end of switches. The argument following this
37 one will be treated as the first arg even if it starts
38 with a -.
39
40 If an arg (or pair of args) has one of the forms described below then
41 it is used by exec to control the flow of input and output among the
42 subprocess(es). Such arguments will not be passed to the subpro‐
43 cess(es). In forms such as “< fileName”, fileName may either be in a
44 separate argument from “<” or in the same argument with no intervening
45 space (i.e. “<fileName”).
46
47 | Separates distinct commands in the pipeline. The stan‐
48 dard output of the preceding command will be piped into
49 the standard input of the next command.
50
51 |& Separates distinct commands in the pipeline. Both stan‐
52 dard output and standard error of the preceding command
53 will be piped into the standard input of the next com‐
54 mand. This form of redirection overrides forms such as
55 2> and >&.
56
57 < fileName The file named by fileName is opened and used as the
58 standard input for the first command in the pipeline.
59
60 <@ fileId FileId must be the identifier for an open file, such as
61 the return value from a previous call to open. It is
62 used as the standard input for the first command in the
63 pipeline. FileId must have been opened for reading.
64
65 << value Value is passed to the first command as its standard in‐
66 put.
67
68 > fileName Standard output from the last command is redirected to
69 the file named fileName, overwriting its previous con‐
70 tents.
71
72 2> fileName Standard error from all commands in the pipeline is
73 redirected to the file named fileName, overwriting its
74 previous contents.
75
76 >& fileName Both standard output from the last command and standard
77 error from all commands are redirected to the file named
78 fileName, overwriting its previous contents.
79
80 >> fileName Standard output from the last command is redirected to
81 the file named fileName, appending to it rather than
82 overwriting it.
83
84 2>> fileName Standard error from all commands in the pipeline is
85 redirected to the file named fileName, appending to it
86 rather than overwriting it.
87
88 >>& fileName Both standard output from the last command and standard
89 error from all commands are redirected to the file named
90 fileName, appending to it rather than overwriting it.
91
92 >@ fileId FileId must be the identifier for an open file, such as
93 the return value from a previous call to open. Standard
94 output from the last command is redirected to fileId's
95 file, which must have been opened for writing.
96
97 2>@ fileId FileId must be the identifier for an open file, such as
98 the return value from a previous call to open. Standard
99 error from all commands in the pipeline is redirected to
100 fileId's file. The file must have been opened for writ‐
101 ing.
102
103 2>@1 Standard error from all commands in the pipeline is
104 redirected to the command result. This operator is only
105 valid at the end of the command pipeline.
106
107 >&@ fileId FileId must be the identifier for an open file, such as
108 the return value from a previous call to open. Both
109 standard output from the last command and standard error
110 from all commands are redirected to fileId's file. The
111 file must have been opened for writing.
112
113 If standard output has not been redirected then the exec command re‐
114 turns the standard output from the last command in the pipeline, unless
115 “2>@1” was specified, in which case standard error is included as well.
116 If any of the commands in the pipeline exit abnormally or are killed or
117 suspended, then exec will return an error and the error message will
118 include the pipeline's output followed by error messages describing the
119 abnormal terminations; the -errorcode return option will contain addi‐
120 tional information about the last abnormal termination encountered. If
121 any of the commands writes to its standard error file and that standard
122 error is not redirected and -ignorestderr is not specified, then exec
123 will return an error; the error message will include the pipeline's
124 standard output, followed by messages about abnormal terminations (if
125 any), followed by the standard error output.
126
127 If the last character of the result or error message is a newline then
128 that character is normally deleted from the result or error message.
129 This is consistent with other Tcl return values, which do not normally
130 end with newlines. However, if -keepnewline is specified then the
131 trailing newline is retained.
132
133 If standard input is not redirected with “<”, “<<” or “<@” then the
134 standard input for the first command in the pipeline is taken from the
135 application's current standard input.
136
137 If the last arg is “&” then the pipeline will be executed in back‐
138 ground. In this case the exec command will return a list whose ele‐
139 ments are the process identifiers for all of the subprocesses in the
140 pipeline. The standard output from the last command in the pipeline
141 will go to the application's standard output if it has not been redi‐
142 rected, and error output from all of the commands in the pipeline will
143 go to the application's standard error file unless redirected.
144
145 The first word in each command is taken as the command name; tilde-sub‐
146 stitution is performed on it, and if the result contains no slashes
147 then the directories in the PATH environment variable are searched for
148 an executable by the given name. If the name contains a slash then it
149 must refer to an executable reachable from the current directory. No
150 “glob” expansion or other shell-like substitutions are performed on the
151 arguments to commands.
152
154 Windows (all versions)
155 Reading from or writing to a socket, using the “@ fileId” nota‐
156 tion, does not work. When reading from a socket, a 16-bit DOS
157 application will hang and a 32-bit application will return imme‐
158 diately with end-of-file. When either type of application
159 writes to a socket, the information is instead sent to the con‐
160 sole, if one is present, or is discarded.
161
162 Note that the current escape resp. quoting of arguments for win‐
163 dows works only with executables using CommandLineToArgv, CRT-
164 library or similar, as well as with the windows batch files (ex‐
165 cepting the newline, see below). Although it is the common es‐
166 cape algorithm, but, in fact, the way how the executable parses
167 the command-line (resp. splits it into single arguments) is de‐
168 cisive.
169
170 Unfortunately, there is currently no way to supply newline char‐
171 acter within an argument to the batch files (.cmd or .bat) or to
172 the command processor (cmd.exe /c), because this causes trunca‐
173 tion of command-line (also the argument chain) on the first new‐
174 line character. But it works properly with an executable (using
175 CommandLineToArgv, etc).
176
177 The Tk console text widget does not provide real standard IO ca‐
178 pabilities. Under Tk, when redirecting from standard input, all
179 applications will see an immediate end-of-file; information
180 redirected to standard output or standard error will be dis‐
181 carded.
182
183 Either forward or backward slashes are accepted as path separa‐
184 tors for arguments to Tcl commands. When executing an applica‐
185 tion, the path name specified for the application may also con‐
186 tain forward or backward slashes as path separators. Bear in
187 mind, however, that most Windows applications accept arguments
188 with forward slashes only as option delimiters and backslashes
189 only in paths. Any arguments to an application that specify a
190 path name with forward slashes will not automatically be con‐
191 verted to use the backslash character. If an argument contains
192 forward slashes as the path separator, it may or may not be rec‐
193 ognized as a path name, depending on the program.
194
195 Two or more forward or backward slashes in a row in a path refer
196 to a network path. For example, a simple concatenation of the
197 root directory c:/ with a subdirectory /windows/system will
198 yield c://windows/system (two slashes together), which refers to
199 the mount point called system on the machine called windows (and
200 the c:/ is ignored), and is not equivalent to c:/windows/system,
201 which describes a directory on the current computer. The file
202 join command should be used to concatenate path components.
203
204 Note that there are two general types of Win32 console applica‐
205 tions:
206
207 [1] CLI — CommandLine Interface, simple stdio ex‐
208 change. netstat.exe for example.
209
210 [2] TUI — Textmode User Interface, any application
211 that accesses the console API for doing such
212 things as cursor movement, setting text color, de‐
213 tecting key presses and mouse movement, etc. An
214 example would be telnet.exe from Windows 2000.
215 These types of applications are not common in a
216 windows environment, but do exist.
217
218 exec will not work well with TUI applications when a console is
219 not present, as is done when launching applications under wish.
220 It is desirable to have console applications hidden and de‐
221 tached. This is a designed-in limitation as exec wants to com‐
222 municate over pipes. The Expect extension addresses this issue
223 when communicating with a TUI application.
224
225 When attempting to execute an application, exec first searches
226 for the name as it was specified. Then, in order, .com, .exe,
227 .bat and .cmd are appended to the end of the specified name and
228 it searches for the longer name. If a directory name was not
229 specified as part of the application name, the following direc‐
230 tories are automatically searched in order when attempting to
231 locate the application:
232
233 • The directory from which the Tcl executable was loaded.
234
235 • The current directory.
236
237 • The Windows 32-bit system directory.
238
239 • The Windows home directory.
240
241 • The directories listed in the path.
242
243 In order to execute shell built-in commands like dir and copy,
244 the caller must prepend the desired command with “cmd.exe /c ”
245 because built-in commands are not implemented using executables.
246
247 Unix (including Mac OS X)
248 The exec command is fully functional and works as described.
249
251 Here are some examples of the use of the exec command on Unix. To exe‐
252 cute a simple program and get its result:
253
254 exec uname -a
255
256 WORKING WITH NON-ZERO RESULTS
257 To execute a program that can return a non-zero result, you should wrap
258 the call to exec in catch and check the contents of the -errorcode re‐
259 turn option if you have an error:
260
261 set status 0
262 if {[catch {exec grep foo bar.txt} results options]} {
263 set details [dict get $options -errorcode]
264 if {[lindex $details 0] eq "CHILDSTATUS"} {
265 set status [lindex $details 2]
266 } else {
267 # Some other error; regenerate it to let caller handle
268 return -options $options -level 0 $results
269 }
270 }
271
272 This is more easily written using the try command, as that makes it │
273 simpler to trap specific types of errors. This is done using code like │
274 this: │
275
276 try { │
277 set results [exec grep foo bar.txt] │
278 set status 0 │
279 } trap CHILDSTATUS {results options} { │
280 set status [lindex [dict get $options -errorcode] 2] │
281 } │
282
283 WORKING WITH QUOTED ARGUMENTS
284 When translating a command from a Unix shell invocation, care should be
285 taken over the fact that single quote characters have no special sig‐
286 nificance to Tcl. Thus:
287
288 awk '{sum += $1} END {print sum}' numbers.list
289
290 would be translated into something like:
291
292 exec awk {{sum += $1} END {print sum}} numbers.list
293
294 WORKING WITH GLOBBING
295 If you are converting invocations involving shell globbing, you should
296 remember that Tcl does not handle globbing or expand things into multi‐
297 ple arguments by default. Instead you should write things like this:
298
299 exec ls -l {*}[glob *.tcl]
300
301 WORKING WITH USER-SUPPLIED SHELL SCRIPT FRAGMENTS
302 One useful technique can be to expose to users of a script the ability
303 to specify a fragment of shell script to execute that will have some
304 data passed in on standard input that was produced by the Tcl program.
305 This is a common technique for using the lpr program for printing. By
306 far the simplest way of doing this is to pass the user's script to the
307 user's shell for processing, as this avoids a lot of complexity with
308 parsing other languages.
309
310 set lprScript [get from user...]
311 set postscriptData [generate somehow...]
312
313 exec $env(SHELL) -c $lprScript << $postscriptData
314
316 Here are some examples of the use of the exec command on Windows. To
317 start an instance of notepad editing a file without waiting for the
318 user to finish editing the file:
319
320 exec notepad myfile.txt &
321
322 To print a text file using notepad:
323
324 exec notepad /p myfile.txt
325
326 WORKING WITH CONSOLE PROGRAMS
327 If a program calls other programs, such as is common with compilers,
328 then you may need to resort to batch files to hide the console windows
329 that sometimes pop up:
330
331 exec cmp.bat somefile.c -o somefile
332
333 With the file cmp.bat looking something like:
334
335 @gcc %*
336
337 or like another variant using single parameters:
338
339 @gcc %1 %2 %3 %4 %5 %6 %7 %8 %9
340
341 WORKING WITH COMMAND BUILT-INS
342 Sometimes you need to be careful, as different programs may have the
343 same name and be in the path. It can then happen that typing a command
344 at the DOS prompt finds a different program than the same command run
345 via exec. This is because of the (documented) differences in behaviour
346 between exec and DOS batch files.
347
348 When in doubt, use the command auto_execok: it will return the complete
349 path to the program as seen by the exec command. This applies espe‐
350 cially when you want to run “internal” commands like dir from a Tcl
351 script (if you just want to list filenames, use the glob command.) To
352 do that, use this:
353
354 exec {*}[auto_execok dir] *.tcl
355
356 WORKING WITH NATIVE FILENAMES
357 Many programs on Windows require filename arguments to be passed in
358 with backslashes as pathname separators. This is done with the help of
359 the file nativename command. For example, to make a directory (on NTFS)
360 encrypted so that only the current user can access it requires use of
361 the CIPHER command, like this:
362
363 set secureDir "~/Desktop/Secure Directory"
364 file mkdir $secureDir
365 exec CIPHER /e /s:[file nativename $secureDir]
366
368 error(n), file(n), open(n)
369
371 execute, pipeline, redirection, subprocess
372
373
374
375Tcl 8.5 exec(n)