1exec(n)                      Tcl Built-In Commands                     exec(n)
2
3
4
5______________________________________________________________________________
6

NAME

8       exec - Invoke subprocesses
9

SYNOPSIS

11       exec ?switches? arg ?arg ...? ?&?
12______________________________________________________________________________
13

DESCRIPTION

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.
19
20       If the initial arguments to exec start with - then they are treated  as
21       command-line  switches  and are not part of the pipeline specification.
22       The following switches are currently supported:
23
24       -ignorestderr
25                    Stops the exec command from treating the  output  of  mes‐
26                    sages to the pipeline's standard error channel as an error
27                    case.
28
29       -keepnewline Retains a trailing newline in the pipeline's output.  Nor‐
30                    mally a trailing newline will be deleted.
31
32       --           Marks  the  end  of switches.  The argument following this
33                    one will be treated as the first arg  even  if  it  starts
34                    with a -.
35
36       If  an  arg (or pair of args) has one of the forms described below then
37       it is used by exec to control the flow of input and  output  among  the
38       subprocess(es).   Such  arguments  will  not  be  passed to the subpro‐
39       cess(es).  In forms such as “< fileName”, fileName may either be  in  a
40       separate  argument from “<” or in the same argument with no intervening
41       space (i.e.  “<fileName”).
42
43       |              Separates distinct commands in the pipeline.  The  stan‐
44                      dard  output of the preceding command will be piped into
45                      the standard input of the next command.
46
47       |&             Separates distinct commands in the pipeline.  Both stan‐
48                      dard  output and standard error of the preceding command
49                      will be piped into the standard input of the  next  com‐
50                      mand.   This form of redirection overrides forms such as
51                      2> and >&.
52
53       < fileName     The file named by fileName is opened  and  used  as  the
54                      standard input for the first command in the pipeline.
55
56       <@ fileId      FileId  must be the identifier for an open file, such as
57                      the return value from a previous call to  open.   It  is
58                      used  as the standard input for the first command in the
59                      pipeline.  FileId must have been opened for reading.
60
61       << value       Value is passed to the first  command  as  its  standard
62                      input.
63
64       > fileName     Standard  output  from the last command is redirected to
65                      the file named fileName, overwriting its  previous  con‐
66                      tents.
67
68       2> fileName    Standard  error  from  all  commands  in the pipeline is
69                      redirected to the file named fileName,  overwriting  its
70                      previous contents.
71
72       >& fileName    Both  standard output from the last command and standard
73                      error from all commands are redirected to the file named
74                      fileName, overwriting its previous contents.
75
76       >> fileName    Standard  output  from the last command is redirected to
77                      the file named fileName, appending  to  it  rather  than
78                      overwriting it.
79
80       2>> fileName   Standard  error  from  all  commands  in the pipeline is
81                      redirected to the file named fileName, appending  to  it
82                      rather than overwriting it.
83
84       >>& fileName   Both  standard output from the last command and standard
85                      error from all commands are redirected to the file named
86                      fileName, appending to it rather than overwriting it.
87
88       >@ fileId      FileId  must be the identifier for an open file, such as
89                      the return value from a previous call to open.  Standard
90                      output  from  the last command is redirected to fileId's
91                      file, which must have been opened for writing.
92
93       2>@ fileId     FileId must be the identifier for an open file, such  as
94                      the return value from a previous call to open.  Standard
95                      error from all commands in the pipeline is redirected to
96                      fileId's file.  The file must have been opened for writ‐
97                      ing.
98
99       2>@1           Standard error from all  commands  in  the  pipeline  is
100                      redirected to the command result.  This operator is only
101                      valid at the end of the command pipeline.
102
103       >&@ fileId     FileId must be the identifier for an open file, such  as
104                      the  return  value  from  a previous call to open.  Both
105                      standard output from the last command and standard error
106                      from  all commands are redirected to fileId's file.  The
107                      file must have been opened for writing.
108
109       If standard output has  not  been  redirected  then  the  exec  command
110       returns  the  standard  output  from  the last command in the pipeline,
111       unless “2>@1” was specified, in which case standard error  is  included
112       as well.  If any of the commands in the pipeline exit abnormally or are
113       killed or suspended, then exec will return an error and the error  mes‐
114       sage  will  include  the  pipeline's  output followed by error messages
115       describing the abnormal terminations; the -errorcode return option will
116       contain  additional  information  about  the  last abnormal termination
117       encountered.  If any of the commands writes to its standard error  file
118       and  that  standard  error  is  not redirected and -ignorestderr is not
119       specified, then exec will return an  error;   the  error  message  will
120       include  the  pipeline's  standard  output,  followed by messages about
121       abnormal terminations (if any), followed by the standard error output.
122
123       If the last character of the result or error message is a newline  then
124       that  character  is  normally deleted from the result or error message.
125       This is consistent with other Tcl return values, which do not  normally
126       end  with  newlines.   However,  if  -keepnewline is specified then the
127       trailing newline is retained.
128
129       If standard input is not redirected with “<”, “<<”  or  “<@”  then  the
130       standard  input for the first command in the pipeline is taken from the
131       application's current standard input.
132
133       If the last arg is “&” then the pipeline  will  be  executed  in  back‐
134       ground.   In  this  case the exec command will return a list whose ele‐
135       ments are the process identifiers for all of the  subprocesses  in  the
136       pipeline.   The  standard  output from the last command in the pipeline
137       will go to the application's standard output if it has not  been  redi‐
138       rected,  and error output from all of the commands in the pipeline will
139       go to the application's standard error file unless redirected.
140
141       The first word in each command is taken as the command name; tilde-sub‐
142       stitution  is  performed  on  it, and if the result contains no slashes
143       then the directories in the PATH environment variable are searched  for
144       an  executable by the given name.  If the name contains a slash then it
145       must refer to an executable reachable from the current  directory.   No
146       “glob” expansion or other shell-like substitutions are performed on the
147       arguments to commands.
148

PORTABILITY ISSUES

150       Windows (all versions)
151              Reading from or writing to a socket, using the “@ fileId”  nota‐
152              tion,  does  not work.  When reading from a socket, a 16-bit DOS
153              application will hang and a 32-bit application will return imme‐
154              diately  with  end-of-file.   When  either  type  of application
155              writes to a socket, the information is instead sent to the  con‐
156              sole, if one is present, or is discarded.
157
158              Note that the current escape resp. quoting of arguments for win‐
159              dows works only with executables using  CommandLineToArgv,  CRT-
160              library  or  similar,  as  well  as with the windows batch files
161              (excepting the newline, see below).  Although it is  the  common
162              escape  algorithm,  but,  in  fact,  the  way how the executable
163              parses the command-line (resp. splits it into single  arguments)
164              is decisive.
165
166              Unfortunately, there is currently no way to supply newline char‐
167              acter within an argument to the batch files (.cmd or .bat) or to
168              the  command processor (cmd.exe /c), because this causes trunca‐
169              tion of command-line (also the argument chain) on the first new‐
170              line character.  But it works properly with an executable (using
171              CommandLineToArgv, etc).
172
173              The Tk console text widget does not  provide  real  standard  IO
174              capabilities.   Under  Tk, when redirecting from standard input,
175              all applications will see an immediate end-of-file;  information
176              redirected  to  standard  output  or standard error will be dis‐
177              carded.
178
179              Either forward or backward slashes are accepted as path  separa‐
180              tors  for arguments to Tcl commands.  When executing an applica‐
181              tion, the path name specified for the application may also  con‐
182              tain  forward  or  backward slashes as path separators.  Bear in
183              mind, however, that most Windows applications  accept  arguments
184              with  forward  slashes only as option delimiters and backslashes
185              only in paths.  Any arguments to an application that  specify  a
186              path  name  with  forward slashes will not automatically be con‐
187              verted to use the backslash character.  If an argument  contains
188              forward slashes as the path separator, it may or may not be rec‐
189              ognized as a path name, depending on the program.
190
191              Additionally, when calling a 16-bit DOS or Windows 3.X  applica‐
192              tion,  all  path  names must use the short, cryptic, path format
193              (e.g., using “applba~1.def”  instead  of  “applbakery.default”),
194              which can be obtained with the “file attributes fileName -short‐
195              name” command.
196
197              Two or more forward or backward slashes in a row in a path refer
198              to  a  network path.  For example, a simple concatenation of the
199              root directory c:/  with  a  subdirectory  /windows/system  will
200              yield c://windows/system (two slashes together), which refers to
201              the mount point called system on the machine called windows (and
202              the c:/ is ignored), and is not equivalent to c:/windows/system,
203              which describes a directory on the current computer.   The  file
204              join command should be used to concatenate path components.
205
206              Note  that there are two general types of Win32 console applica‐
207              tions:
208
209                     [1]    CLI  —   CommandLine   Interface,   simple   stdio
210                            exchange. netstat.exe for example.
211
212                     [2]    TUI  —  Textmode  User  Interface, any application
213                            that accesses  the  console  API  for  doing  such
214                            things  as  cursor  movement,  setting text color,
215                            detecting key presses and mouse movement, etc.  An
216                            example  would  be  telnet.exe  from Windows 2000.
217                            These types of applications are not  common  in  a
218                            windows environment, but do exist.
219
220              exec  will not work well with TUI applications when a console is
221              not present, as is done when launching applications under  wish.
222              It   is  desirable  to  have  console  applications  hidden  and
223              detached.  This is a designed-in limitation  as  exec  wants  to
224              communicate  over  pipes.   The  Expect extension addresses this
225              issue when communicating with a TUI application.
226
227              When attempting to execute an application, exec  first  searches
228              for  the  name as it was specified.  Then, in order, .com, .exe,
229              .bat and .cmd are appended to the end of the specified name  and
230              it  searches  for  the longer name.  If a directory name was not
231              specified as part of the application name, the following  direc‐
232              tories  are  automatically  searched in order when attempting to
233              locate the application:
234
235              ·  The directory from which the Tcl executable was loaded.
236
237              ·  The current directory.
238
239              ·  The Windows NT 32-bit system directory.
240
241              ·  The Windows NT 16-bit system directory.
242
243              ·  The Windows NT home directory.
244
245              ·  The directories listed in the path.
246
247              In order to execute shell built-in commands like dir  and  copy,
248              the  caller  must prepend the desired command with “cmd.exe /c 
249              because built-in commands are not implemented using executables.
250
251       Unix (including Mac OS X)
252              The exec command is fully functional and works as described.
253

UNIX EXAMPLES

255       Here are some examples of the use of the exec command on Unix.  To exe‐
256       cute a simple program and get its result:
257
258              exec uname -a
259
260   WORKING WITH NON-ZERO RESULTS
261       To execute a program that can return a non-zero result, you should wrap
262       the call to exec in catch and check  the  contents  of  the  -errorcode
263       return option if you have an error:
264
265              set status 0
266              if {[catch {exec grep foo bar.txt} results options]} {
267                  set details [dict get $options -errorcode]
268                  if {[lindex $details 0] eq "CHILDSTATUS"} {
269                      set status [lindex $details 2]
270                  } else {
271                      # Some other error; regenerate it to let caller handle
272                      return -options $options -level 0 $results
273                  }
274              }
275
276       This  is  more  easily  written using the try command, as that makes it │
277       simpler to trap specific types of errors. This is done using code  like │
278       this:                                                                   │
279
280              try {                                                            │
281                  set results [exec grep foo bar.txt]                          │
282                  set status 0                                                 │
283              } trap CHILDSTATUS {results options} {                           │
284                  set status [lindex [dict get $options -errorcode] 2]         │
285              }                                                                │
286
287   WORKING WITH QUOTED ARGUMENTS
288       When translating a command from a Unix shell invocation, care should be
289       taken over the fact that single quote characters have no  special  sig‐
290       nificance to Tcl.  Thus:
291
292              awk '{sum += $1} END {print sum}' numbers.list
293
294       would be translated into something like:
295
296              exec awk {{sum += $1} END {print sum}} numbers.list
297
298   WORKING WITH GLOBBING
299       If  you are converting invocations involving shell globbing, you should
300       remember that Tcl does not handle globbing or expand things into multi‐
301       ple arguments by default.  Instead you should write things like this:
302
303              exec ls -l {*}[glob *.tcl]
304
305   WORKING WITH USER-SUPPLIED SHELL SCRIPT FRAGMENTS
306       One  useful technique can be to expose to users of a script the ability
307       to specify a fragment of shell script to execute that  will  have  some
308       data  passed in on standard input that was produced by the Tcl program.
309       This is a common technique for using the lpr program for  printing.  By
310       far  the simplest way of doing this is to pass the user's script to the
311       user's shell for processing, as this avoids a lot  of  complexity  with
312       parsing other languages.
313
314              set lprScript [get from user...]
315              set postscriptData [generate somehow...]
316
317              exec $env(SHELL) -c $lprScript << $postscriptData
318

WINDOWS EXAMPLES

320       Here  are  some examples of the use of the exec command on Windows.  To
321       start an instance of notepad editing a file  without  waiting  for  the
322       user to finish editing the file:
323
324              exec notepad myfile.txt &
325
326       To print a text file using notepad:
327
328              exec notepad /p myfile.txt
329
330   WORKING WITH CONSOLE PROGRAMS
331       If  a  program  calls other programs, such as is common with compilers,
332       then you may need to resort to batch files to hide the console  windows
333       that sometimes pop up:
334
335              exec cmp.bat somefile.c -o somefile
336
337       With the file cmp.bat looking something like:
338
339              @gcc %*
340       or like another variant using single parameters:
341              @gcc %1 %2 %3 %4 %5 %6 %7 %8 %9
342
343   WORKING WITH COMMAND BUILT-INS
344       Sometimes  you  need  to be careful, as different programs may have the
345       same name and be in the path. It can then happen that typing a  command
346       at  the  DOS prompt finds a different program than the same command run
347       via exec. This is because of the (documented) differences in  behaviour
348       between exec and DOS batch files.
349
350       When in doubt, use the command auto_execok: it will return the complete
351       path to the program as seen by the exec command.   This  applies  espe‐
352       cially  when  you  want  to run “internal” commands like dir from a Tcl
353       script (if you just want to list filenames, use the glob command.)   To
354       do that, use this:
355
356              exec {*}[auto_execok dir] *.tcl
357
358   WORKING WITH NATIVE FILENAMES
359       Many  programs  on  Windows  require filename arguments to be passed in
360       with backslashes as pathname separators. This is done with the help  of
361       the file nativename command. For example, to make a directory (on NTFS)
362       encrypted so that only the current user can access it requires  use  of
363       the CIPHER command, like this:
364
365              set secureDir "~/Desktop/Secure Directory"
366              file mkdir $secureDir
367              exec CIPHER /e /s:[file nativename $secureDir]
368

SEE ALSO

370       error(n), file(n), open(n)
371

KEYWORDS

373       execute, pipeline, redirection, subprocess
374
375
376
377Tcl                                   8.5                              exec(n)
Impressum