0% found this document useful (0 votes)
129 views

Seta24 Setb15 Set C 23 Set D 85

This document provides an overview of the Tcl programming language syntax and features. It discusses topics such as commands, variables, expressions, control flow, data structures and more. The key points covered are that Tcl commands are separated by newlines or semicolons, variables are assigned using the set command, expressions can be evaluated using the expr command, and control structures like if/else, for/while/foreach loops are supported to control program flow. Tcl also provides data structures like strings that can be manipulated using commands.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views

Seta24 Setb15 Set C 23 Set D 85

This document provides an overview of the Tcl programming language syntax and features. It discusses topics such as commands, variables, expressions, control flow, data structures and more. The key points covered are that Tcl commands are separated by newlines or semicolons, variables are assigned using the set command, expressions can be evaluated using the expr command, and control structures like if/else, for/while/foreach loops are supported to control program flow. Tcl also provides data structures like strings that can be manipulated using commands.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 37

Introduction

Language Syntax

• 1Commands are separated by newlines or semicolons.


set a 24
set b 15
set c 23; set d 85

• 2Comments are indicated by a # as the first nonblank character


of a command.
# This is a comment line
set a 24 ; # Also a comment
set b 18 # NOT a comment

• 3Tcl parses a command and makes substitutions in a single pass


from left to right. At most a single layer of substitution
occurs for each character. That is, the result of one
substitution is not scanned for further substitutions.
set a 23;
set b “A = $a”;
puts $b ==> A = $a

• 4Types of Substitution

1 - Variable substitution is triggered by a dollar sign


character or ${variable_name} syntax, when the
variable name is ambiguous. It causes the value of the
Tcl variable to be inserted.
set a 24;
expr $a*2; ==> 48
set p Pre;
set w ${p}fix ==> Prefix

1 - Command substitution causes part or all of a word to be


replaced with the result of a Tcl command. It is invoked
by enclosing the command in square brackets.
set a [expr 24*2]; ==> 48

1 - Backslash substitution is used to insert special characters


such as newlines into words and also to insert characters
as [ and $ without them being treated specially by the
Tcl parser.
set cost \$200.00; ==> $200.00

1 - Double Quotes disable word and command separators


(spaces, tabs, newlines, and semicolons). Variable,
command and backslash substitution all occur as usual.

set w 10; set l 15;


set msg “Area is [expr $w*$l]”;
==> Area is 150

1 - Brace Quotes disable almost all substitutions. All special


characters, spaces, tabs, newlines and semicolons are all
treated as ordinary characters. Except \ newline, as used
to contiue a command on the next line. One of the most
important uses is for deferred command evaluation.

set cmds {set b $c; set d 3}


==> set b $c; set d 3
set c 4
eval $cmds
set b ==> 4
Variables

• 1set
command assigns a value to a variable
set varName ?value?
set a 23; ==> 23
set msg “Hello World”; ==> Hello World
set msg ==> Hello World
• 2Variable Substitution
is triggered by the presence of an unquoted $ character.
set a 23; ==> 23
expr $a+2; ==> 25
• 3unset
command removes the variable.
unset varName ?varName varName?
unset a msg;
set msg ==>
• 4info exists
command test for the existence of a variable. It returns a 1
if the variable exists in the current context, 0 otherwise.
info exists varName
set a 32;
info exists a; ==> 1
unset a;
info exists a; ==> 0
• 5incr
command adds the specified integer to the variable’s value
and stores the value back into the variable.
incr varName ?increment?
set i 1;
incr i 3; ==> 4
set j 12;
incr j -2; ==> 10
incr j; ==> 11
• 6append
command adds text to the end of a variable in a way that
avoids character copying.
append varName value ?value ...?
set Msg “IOplace: ”
append Msg “Severe Error”
==> IOplace: Severe Error
• 7Predefined Variables
• 8argv0 contains the Tcl script name
• 9argc contains the number of arguments
• 10argv contains a list of the arguments
• 11env(Environment_Variable_Name) contains the value of the
specified environment variable.
args.tcl:

#!/usr/local/bin/tclsh
puts “The command name is \”$argv0\””
puts “There are $argc arguments: \ $argv”
puts “User is $env(USER)”
exit

> args.tcl p1 p2 p3
The command name is args.tcl
There are 3 arguments: p1 p2 p3
User is forman
Expressions

Expressions combine values (or operands) with operators to


produce new values.
• 12expr
command evaluates its arguments as an expression and
returns the result as a string.
expr arg ?arg arg ...?
expr 2.3 * (24-7) ==> 39.1
• 13Operands are integer strings, real number strings or
character strings. If an expression has operands of dif-
ferent types, Tcl converts one type to the other.
• 14Integers default to decimal, but if the first character is a 0 the
number is read in octal (base 8) and if the first two characters
are 0x, the number is read in hexadecimal (base 16).
243, 0363, 0xF3 ==> 243 decimal
• 15Real operands may be specified using most of the forms defined
for ANSI C.
5.5 3.7e+6 6E4 3.
• 16Operators & Precedence
Table 1: Operators & Precedence

Syntax Result Operand


Types
-a Negative of a int, real
!a Logical NOT: 1 if a is zero, 0 otherwise int, real
~a Bit-wise complement of a int
a*b Multiply a and b int, real
a/b Divide a and b int, real
a%b Remainder after dividing a by b int
a+b Add a and b int, real
a-b Subtract a and b int, real
a<<b Left-shift a by b bits int
a>>b Arithmetic right-shift a by b bits int
a<b 1 if a is less than b, 0 otherwise int, real,
a>b 1 if a is greater than b, 0 otherwise string
a<=b 1 if a is less than or equal to b, 0 int, real,
a>=b otherwise string
1 if a is greater than or equal to b, 0 int, real,
otherwise string
int, real,
string
a==b 1 if a is equal to b, 0 otherwise int, real,
a!=b 1 if a is NOT equal to b, 0 otherwise string
int, real,
string
a&b Bit-wise AND of a and b int
a^b Bit-wise exclusive OR of a and b int
a|b Bit-wise OR of a and b int
a&&b Logical AND: 1 if both a and b are non- int, real
zero, 0 otherwise
a||b Logical OR: 1 if either a or b is non- int, real
zero, 0 otherwise
a?b:c Choice: if a is non-zero then b, else c a: int, real

expr !2 ==> 0
expr 3*4 ==> 12
expr 5 < 4 ==> 0
expr 0x55&0xAA ==> 0xFF
expr 1?”A”:”B” ==> A
NOTE: Several math functions, such as
sin(x) and log(x) exist. See
references for details.
Control Flow

Table 1: if
command evaluates an expression, tests the results and if it is
non-zero, executes a script.
if test1 body1 ?elseif test2 body2 ...? ?else bodyn?
if {$x == 0} { set y 23 }
if {$y > 12} {
...
} elseif {$z < 2} {
...
} else {
... }
Table 1: while
command evaluates an expression and if the result is nonzero
then it executes the Tcl script. It repeats the processes until
the expression evaluates to zero.
while test body
set i 0
while { $i < 10 } {
puts “I=$i”
incr i
}
Table 1: for
command executes its initialization script, then evaluates its
test. If it evaluates to nonzero, then it executes its body script,
executes it reinit script and then reevaluates its test. It repeats
the process until the test evaluates to zero.
for init test reinit body
for {set i 0} {$i<10} {incr i} {
puts “I=$i”
}
Table 1: foreach
command evaluates its body script for each item in a list.
foreach varName list body
set users “John Scott Jerry”
foreach name $users {
puts “Name=$name”
}
Table 1: break
command terminates the innermost nested looping command
Table 1: continue
command terminates the current iteration of the innermost
looping command and goes on to the next iteration of that
command.

Table 1: switch
command tests a value against a number of patterns and
executes one of several Tcl scripts.
switch ?options? string {pattern body ?pattern body ...?}
options may be -exact, -glob, -regexp, or -- to indicate the end of
options.
switch $rotation {
ROT000 { set side “Bottom” }
ROT090 { set side “Right” }
ROT180 { set side “Top” }
ROT270 { set side “Left” }
default { set side “Error” }
}
switch -exact -- $option {
-p { set imagePDLname $arg }
-i -
-io { set placeFileName $arg }
default { puts “Error: invalid
option $option” }
}

Table 1: eval
command executes its arguments as a Tcl script.
eval arg ?arg arg ...?
set cmd “set a 0”
eval $cmd ==> 0
set cmd2 “Set b \$a”
set c [eval $cmd2] ==> 0

Table 1: source
command executes the contents of the specified file. It returns
the return value of the last command executed in the file. It
also allows a return command in the file to terminate
processing of the file.
source utilities.tcl
Data Structures

Strings
Strings are an ordered collection of characters. Tcl stores strings
using null (zero) character for termination.
Table 1: string length
command returns the number of characters in the specified
string.
string length string
string length “Hello World” ==> 11
Table 1: string index
command returns the charIndex’th character of string.
string index string charIndex
string index “Hello World” 5 ==> o
Table 1: string first
command returns the index in string2 of the first character in
the leftmost substring that exactly matches string1 or -1 if
there is no match.
string first string1 string2
set str “Outline=(100,100,(-100,-100))”
string first “(“ $str ==> 9
string first “,(“ $str ==> 17
Table 1: string last
command returns the index in string2 of the first character in
the rightmost substring that exactly matches string1 or -1 if
there is no match.
string last string1 string2
set str “Outline=(100,100,(-100,-100))”
string last “)“ $str ==> 29
Table 1: string range
command returns the substring of string that lies between the
indices given by first and last, inclusive.
string range string first last
set str “Outline=(100,100,(-100,-100))”
set tuple [string range $str 10 29]
==> 100,100,(-100,-100)
Table 1: string tolower
command returns a string which has been converted to all
lower case characters.
string tolower string
set lcase [string tolower “AbCdEf”
==> abcdef
Table 1: string toupper
command returns a string which has been converted to all
upper case characters.
string toupper string
sting toupper “AbCdEf” ==> ABCDEF
Table 1: string trim
command returns a string which has had specified leading and
trailing characters removed. The default characters for
removal are space, tab, newline, and carriage return.
string trim string ?chars?
set str “ PDLLengthUnit = MICRON;“
set str [string trim $str]
set str [string trim $str “;”]
Table 1: string trimleft
command returns a string which has had specified leading
characters removed.
string trimleft string ?chars?
set str “(100,100,(-100,-100))”
set str [string trimleft “(“]
==> 100,100,(-100,-100))
Table 1: string trimright
command returns a string which has had specified trailing
characters removed.
string trimright string ?chars?
set str “100,100,(-100,-100))”
set str [string trimright “)“]
==> 100,100,(-100,-100

Table 1: string compare


command compares two strings lexicographically and returns
a -1, 0, or 1 if the first string is less than, equal, or greater than
the second, respectively.
string compare string1 string2
set coor1 “(100,100)”
set coor2 “(100,200)”
string compare $coor1 $coor2 ==> -1

Table 1: string match


command compares a string to a glob-style pattern and
returns a 1 if the pattern matches and 0 otherwise.
string match pattern string
Table 1: Glob Style Special Characters

Character Description
* Matches any seqence of zero or more characters
? Matches any single character
[chars] Matches any single character in chars. If chars
contains a sequence of the form a-b, any character
between a and b, inclusive will match.
\x Matches the single character x. This provides a
way to put the special characters *, ?, [,], and \ in
the pattern.

set str “ControlInformation = {“


string match Control* $str ==> 1

Table 1: regexp
command compares a string to a regular expression and
returns 1 if the pattern matches and 0 otherwise. The -nocase
option indicates that case should be ignored.
regexp ?-nocase? ?--? exp string
Table 1: Regular Expression Special Characters

Character Description
. Matches any single character
^ Matches the null string at the start of the string
$ Matches the null string at the end of the string
[chars] Matches any single character from chars. If the
first character of chars is ^, the pattern matches
any single character NOT in the remainder of
chars. A sequence of the form a-b in chars is
treated as all the characters between a and b,
inclusive.
(regexp) Matches anything that matches the regular
expression regexp.
* Matches a sequence of 0 or more matches of the
preceding atom.
+ Matches a sequence of 1 or more matches of the
preceding atom.
? Matches either a null string or a match of the
preceding atom.
regexp1| Matches anything that matches either regexp1 or
regexp2 regexp2

set str “PDLLength = MICRON // Default”


regexp {.+[/][/](.)+} $str ==> 1

set str2 “ /* This is a comment. */”


reg exp {^[/][*].+[*][/]$} $str2 ==> 1
reg exp {^[/][*].+[*][/]$} $str ==> 0
Table 1: format
command replaces % sequences in a string with values and
returns the new string.
format formatString ?value value...?
Table 1: Format/Scan Conversions

Character Description
d Signed Integer
u Unsigned Integer (Format command only)
i Signed Integer. The argument may be in hex (0x) or
octal (0) format.
o Unsigned Octal.
x or X Unsigned hexadecimal. ‘x’ gives lower-case results.
c Map from an integer to the ASCII character it
represents.
s A string.
f Floating Point number in the format a.b.
e or E Floating point number in scientific notation, a.bE+/-
c.
g or G Floating point number in either %f or %e format,
whichever is shorter.

set w 10; set l=8


format “Width=%u, Length=%i” $w $l
==> Width=10, Length=8

set Emsg “Invalid argument.”


format “%s (E) %s” $argv0 $Emsg
==> name.tcl (E) Invalid argument.

Table 1: Format Flags

Character Description
- Left justify the field
+ Always include a sign, either + or -.
space Precede a number with a space, unless the number
has a leading sign.
0 Pad with zeros.
# Leading 0 for octal. Leading 0x for hex. Always
include a decimal point in floating point. Do not
remove trailing zeros (%g).
Table 1: scan
command parses a string, using fields specified in a format
string, placing values that match % sequences into specified
variables.
scan string format varName ?VarName ...?

set str “AreaUsagePattern = T3T57 ;”


scan $str “%s %s %s” key eq value
puts “Key=$key, Eq=$eq, Value=$value”
==> Key=AreaUsagePattern, Eq==,
Value=T3T57

Lists
List are an ordered collection of elements where each element
can have any string value. Elements of a list can themselves be
lists.
set nameList John Jerry Joe
==> John Jerry Joe
set nameList { John Jerry {Mary Joe }}
==> John Jerry {Mary Joe}

Table 1: list
command returns a list whose elements are the command
arguments.
list value ?value ...?
list {a b c} {d e} f {g h}
==> {a b c} {d e} f {g h}
Table 1: concat
command takes any number of lists as arguments and joins all
the elements into a single list.
concat list ?list ...?
concat {a b c} {d e} f {g h}
==> a b c d e f g h

Table 1: llength
command returns the number of elements in a list.
llength list
llength {{a b c} {d e} f {g h}} ==> 4
llength John ==> 1
llength {} ==> 0
Table 1: lindex
command returns the index’th element of the list (0 refers to
the first element).
lindex list index
set cList {{a b c} {d e} f {g h}}
lindex $cList 2 ==> f
lindex $cList 0 ==> a b c
Table 1: lrange
command returns a list consisting of elements first through
last of list.
lrange list first last
lrange $cList 0 1 ==> {a b c} {d e}
lrange $cList 2 end ==> f {g h}
Table 1: lappend
command provides an efficient way to append new elements to
a list stored in a variable.
lappend varName value ?value ...?
lappend cList x y z
==> {a b c} {d e} f {g h} x y z
Table 1: split
command breaks a string into component pieces so that you
can process the pieces independently. It returns a list whose
elements are the pieces.
split string ?splitChars?
set y /u/home/tcl/lists.tcl
split $y / ==> u home tcl lists.tcl
Table 1: join
command concatenates the elements of a list with the specified
separator between them, to form a string.
join list ?joinString?
set x {5 12 7}
expr [join $x +] ==> 24

Arrays
Table 1: An array is a collection of elements, each of which is a
variable with its own name and value. Both array names
and element names may be arbitrary strings.
set Position(USAGE_A) “0,200”;
set Usage “USAGE_A”;
set xypos $Position($Usage); ==>0,200
Table 1: Multidimensional arrays can be simulated by concate-
nating multiple indices into a single element name.
set i 10; set j 20;
set matrix($i,$j) 254;
set value $matrix($i,$j); ==> 254
Table 1: array size
command returns the number of elements in an array.
array size arrayName
array size env ==> 21
Table 1: array names
command returns a list of the names of all the elements in an
array.
array names arrayName
array names env ==> HOME MANPATH ...
Table 1: Other array commands exist for searching through
arrays.
Input/Output Operations

Tcl I/O commands are very similar to “C” I/O library pro-
cedures. First the file must be opened, then data can be read or
written, and then the file must be closed.
Table 1: open
command is used to open the specified file. The access to the
file is controlled by passing an access flag. It returns a file ID
which can be used to access the file stream.
open name ?access? ?permissions?

Table 1: Open POSIX Access Flags

RDONLY Open for reading.


WRONLY Open for writing.
RDWR Open for reading and writing
APPEND Open for append.
CREAT Create the file if it does not exist.
EXCL If CREAT is also specified, the file cannot already
exist.
TRUNC Truncate the file if it exists.
NOCTTY Prevent terminal devices from becoming the
controlling terminal.
NONBLOCK Do not block during the open.

Table 1: Open Access Flags

Character Description
r Open for reading. File must exist.
r+ Open for reading and writing. The file must exist.
w Open for writing. Truncate if it exists. Create if it
does not exist.
w+ Open for reading and writing. Truncate or create.
a Open for writing. The file must exist. Data is
appended to the file.
a+ Open for reading and writing. File must exist. Data
is appended.

set wFile [open $wFile w 0755 ]


set wF [open $wF {WRONLY CREAT} 0755]

Table 1: close
command closes the file stream.
close fileId

Table 1: flush
command writes any buffered output that has been generated
for the specified file stream.
flush fileId

Table 1: puts
command writes a string to a I/O stream, appending newline
character unless the -nonewline option is specified. The
default I/O stream is stdout.
puts ?-nonewline? ?fileId? string
Table 1: gets
command reads a line from an I/O steam and places it into the
specified variable. It returns the number of characters read
or -1 if the end of file is reached. The default I/O stream is
stdin.
gets fileId ?varName?
#!/usr/local/bin/tclsh
# Unix cp like command in Tcl
set infID [open [lindex $argv 0]]
set outfID [open [lindex $argv 1] w]
while {[gets $infID line] >= 0} {
puts $outfID $line
}
close $infID
close $outfID

Table 1: cd
command changes the current working directory to the
specified directory or $HOME in none is specified.
cd ?dirName?
cd ==> /u/forman
Table 1: pwd
command returns the full path of the current working
directory.
pwd
pwd ==> /u/forman
Table 1: glob
command returns a list of names of all the files that match any
of the specified glob style patterns. An error occurs, if
-nocomplain is not specified and the returned list is empty.
glob ?-nocomplain? ?--? pattern
?pattern...?
glob -nocomplain *.tcl
==> abc.tcl even.tcl hello.tcl
Table 1: file exists
command returns 1 if the specified file exists and the current
user has search privilege for the directories leading to it, 0
otherwise.
file exists fileName
file exists /u/forman/.login ==> 1
Table 1: file readable
command
returns 1 if the file is readable by the current user, 0 oth-
erwise.
file readable fileName
file readable /u/forman/.login ==> 1
Table 1: file writable
command returns 1 if the file is writable by the current user, 0
otherwise.
file writable fileName
file writable /u/joes/file.txt ==> 0
Table 1: file executable
command returns 1 if the file is executable by the current
user, 0 otherwise.
file executable fileName
file executable /u/forman/hello.tcl
==> 1
Table 1: file owned
command returns 1 if the file is owned by the current user, 0
otherwise.
file owned fileName
file owned /u/joes/private/file.txt
==> 0
Table 1: file isfile
command returns 1 if the specified file is an ordinary file, 0
otherwise.
file isfile fileName
file isfile /u/forman/hello.tcl
==> 1
Table 1: file isdirectory
command returns 1 if the specified file is a directory, 0
otherwise.
file isdirectory fileName
file isdirectory /u/forman/hello.tcl
==> 0
file isdirectory /u/forman ==> 1
Table 1: file type
command returns a string giving the type of the specified file.
Its value will be one of file, directory, characterSpecial,
blockSpecial, fifo, link, or socket.
file type fileName
file type /u/forman/hello.tcl
==> file

Table 1: file dirname


command returns all the characters in the specified file name
up to but not including the last / character. Returns . if the file
name contains no slashes, / if the last slash is the first
character.
file dirname fileName
file dirname /u/forman/hello.tcl
==> /u/forman

Table 1: file tail


command returns all the characters in the specified file after
the last / character. Returns the specified file name if it
contains no slashes.
file tail fileName
file tail /u/forman/hello.tcl
==> hello.tcl
Table 1: file extension
command returns all of the characters in the specified file
name after and including the last dot. Returns an empty
string if there is no dot or no dot after the last slash.
file extension fileName
file extension /u/forman/hello.tcl
==> .tcl
Table 1: file rootname
command returns all of the characters in the specified file
name up to but not including the last dot. Returns the
specified file name if it doesn’t contain any dots after the last
slash.
file rootname fileName
file rootname /u/forman/hello.tcl
==> /u/forman/hello
Table 1: Other file commands
file size fileName
file atime fileName
file mtime fileName
file lstat fileName arrayName
file stat fileName arrayName
file readlink fileName
Procedures

A Tcl procedure is a command which is implemented as a Tcl


script rather than C code. New commands/procedures are
defined using the “proc” command. Additional commands exist
handling variable passing and scoping.
Table 1: proc
command defines a procedure with the specified name,
replacing any existing command by that name.
proc name arglist body
proc abc {a b c} {
expr $a*$b+$c
}
abc 4 6 3 ==> 27

Table 1: A procedure with no arguments is defined with an


empty list “{}”, as the argument list.
proc HelpText {} {
puts “abc.tcl (I) abc.tcl a b c”
}

HelpText
==> abc.tcl (I) abc.tcl a b c
Table 1: Defaults for procedure arguments can be defined using
a sublist which contains the arguments name and its default
value. Arguments with defaults, after any arguments
without defaults, are optional.

proc abc {a {b 1} {c 0}} {


expr $a*$b+$c
}
abc 6 4 ==> 24
abc 6 ==> 6
abc 6 4 2 ==> 26

Table 1: Variable number of arguments is supported by using


the special name args as the last element in the argument
list.

proc sum args {


expr [join $args +]
}

sum 1 2 3 ==> 6
sum 1 2 3 4 5 6 7 8 9 ==> 45

Table 1: return
command returns from the innermost nested procedure or
source command with the specified value as the result of the
procedure. If no value is specified, an empty string is
returned.
return ?value?

proc inrange {min max tst} {


if {($tst<$max)&&($tst>$min)} {
return 1
} else {
return 0
}
}

inrange 10 20 11 ==> 1
Table 1: When a Tcl procedure is executed it uses a local set a
variables. Variables referenced outside of any procedure
are called global variables. A procedure can reference
global variables using the global command.
Table 2: global
command binds local variables to global variables with the
same name.
global name1 ?name2 ...?

proc HelpText {} {
global argv0
puts “$argv0 (I) $argv0 a b c”
}

HelpText
==> hello.tcl (I) hello.tcl a b c
Table 1: A Tcl procedure can reference variables within its call
stack by using the upvar command. This command is also
useful for passing arrays and large lists to a procedure.

Table 1: upvar
command binds local variables to variables at the specified
stack level. The stack level consists of a number or a number
preceded by #, and defaults to 1. #0 specifies that the local
variables are bound to global variables.

upvar ?level? name1 localName1


?name2 localName2...?

proc printArray {ArrayName} {


upvar #1 $ArrayName aName
foreach key [array names aName] {
puts “$key = $aName($key)”
}

printArray env
==> HOME = /u/forman
==> MANPATH = /usr/man:/usr/local/man
...
Table 1: uplevel
command evaluates its arguments, like eval, but in the
variable context of the specified stack level. This command is
useful in the generation of control structures.
uplevel ?level? arg ?arg ...?
proc do {Counter first last body} {
upvar $Counter cnt
for {set cnt $first} {$cnt<=$last} \
{incr cnt} {
uplevel $body
}
}
do i 2 4 {
puts “Count=$i”
}
puts “Last Count=$i”

==> Count=2
==> Count=3
==> Count=4
==> Last Count=4

NOTE: This “do” command does not


handle the continue or break
command correctly.
Processes

Non Tcl programs can be executed and their stdout results


returned using the Tcl “exec” command. New processes can also
be created using the “open” command which supports
communication between processes using file I/O commands.
Table 1: exec
command executes the command pipeline specified as its
arguments and returns the pipeline’s standard output or an
empty string if output is redirected. The final newline
character if any is truncated unless the -keepnewline option is
specified. If the last argument is &, the pipeline is executed in
the background and the return value is a list of its process ids.
exec ?-keepnewline? ?--? arg ?arg ...?

set tclFiles [exec ls | grep .tcl]

==> abc.tcl
==> even.tcl
==> hello.tcl

[exec cat < file1 file2 | grep Tcl \


> file3]

[exec cat < file* | grep Tcl \


> file3]
==> Error

NOTE: exec does not perform Unix shell


file name expansions.
[exec ksh -c cat < file* | grep Tcl \
> file3]

Table 1: I/O redirection Symbols

>file Write standard output to file, replacing the file.


>>file Append standard output to file.
>@fileID Redirects standard output to the open file specified
by fileID.
>&file Redirects both standard output and error to file.
2>file Redirects standard error to file.
<file Causes standard input to be taken from file.
<<value Passes an immediate value to the subprocess as its
standard input.
<@fileID Causes standard input to be taken from the open file
specified by fileID.
| Redirect standard output from a subprocess to the
standard input of another subprocess.

Table 1: exit
command terminates the current process returning an integer
return code to the parent. The return code defaults to 0 if not
specified.
exit ?returnCode?

exit 3
Table 1: open
command can be used to create pipes to subprocesses. The
access to the subprocesses is controlled by passing an access
flag. It returns a file ID which can be used to communicate
with the subprocess with the gets and puts commands.
open |command ?access?

set fID [open {|ls | grep .tcl} r]


while {[gets $fID line] >= 0} {
puts “Tcl: $line”
}

==> Tcl: abc.tcl


==> Tcl: even.tcl
==> Tcl: hello.tcl

Table 1: pid
command returns a list of all the process IDs in the pipeline
associated with the specified file ID (opened using |). If no file
ID is specified it returns the process ID of the current process.
pid ?fileID?
pid ==> 19136

You might also like