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

UNIX EXAMPLES

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

WINDOWS EXAMPLES

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

SEE ALSO

353       error(n), file(n), open(n)
354

KEYWORDS

356       execute, pipeline, redirection, subprocess
357
358
359
360Tcl                                   8.5                              exec(n)
Impressum