Escolar Documentos
Profissional Documentos
Cultura Documentos
Quick Reference
1
Surya Gadde
Table of Contents
Simple Text output (puts command) ........................................................................................................ 6
Assigning values to variables (set command) ........................................................................................... 6
Evaluations and Substitutions ................................................................................................................... 6
Using (Quotes) ................................................................................................................................. 6
Using {} (braces) .................................................................................................................................... 7
Using [ ] (Brackets) ................................................................................................................................ 7
Math functions .......................................................................................................................................... 8
Switch command....................................................................................................................................... 9
If command ............................................................................................................................................. 10
A simple if command ........................................................................................................................ 10
If..else command................................................................................................................................. 10
If elseif.else command ................................................................................................................... 10
While Loop .............................................................................................................................................. 10
For loop ................................................................................................................................................... 11
Procedures .............................................................................................................................................. 11
Global ...................................................................................................................................................... 12
Upvar ....................................................................................................................................................... 13
List ........................................................................................................................................................... 15
lindex ................................................................................................................................................... 15
llength ................................................................................................................................................. 15
lappend ............................................................................................................................................... 16
linsert .................................................................................................................................................. 16
lreplace................................................................................................................................................ 16
lsearch ................................................................................................................................................. 17
lsort ..................................................................................................................................................... 17
lrange .................................................................................................................................................. 18
concat.................................................................................................................................................. 18
String command ...................................................................................................................................... 19
string length ........................................................................................................................................ 19
string index.......................................................................................................................................... 19
string range ......................................................................................................................................... 19
string compare .................................................................................................................................... 19
string first ............................................................................................................................................ 20
string last ............................................................................................................................................. 20
string wordstart .................................................................................................................................. 21
string wordend .................................................................................................................................... 21
string match ........................................................................................................................................ 21
string tolower ...................................................................................................................................... 22
string toupper ..................................................................................................................................... 22
string totitle ........................................................................................................................................ 22
string trim............................................................................................................................................ 22
string trimleft ...................................................................................................................................... 22
string trimright .................................................................................................................................... 23
format ..................................................................................................................................................... 23
regexp ..................................................................................................................................................... 24
regsub ..................................................................................................................................................... 25
Array........................................................................................................................................................ 25
array exists .......................................................................................................................................... 25
array names ........................................................................................................................................ 26
array size ............................................................................................................................................. 26
array get .............................................................................................................................................. 26
array set .............................................................................................................................................. 26
array startsearch ................................................................................................................................. 27
array nextelement............................................................................................................................... 27
array anymore ..................................................................................................................................... 28
array donesearch ................................................................................................................................ 28
Accessing Files......................................................................................................................................... 29
Open.................................................................................................................................................... 29
Close .................................................................................................................................................... 29
Gets ..................................................................................................................................................... 29
Puts ..................................................................................................................................................... 30
3
Read .................................................................................................................................................... 30
Seek ..................................................................................................................................................... 30
tell ....................................................................................................................................................... 31
flush..................................................................................................................................................... 31
eof ....................................................................................................................................................... 31
Glob ......................................................................................................................................................... 33
File status ................................................................................................................................................ 34
file size................................................................................................................................................. 34
file atime ............................................................................................................................................. 34
file mtime ............................................................................................................................................ 34
file exists ............................................................................................................................................. 34
File isdirectory ..................................................................................................................................... 35
file isfile ............................................................................................................................................... 35
file owned ........................................................................................................................................... 35
file executable ..................................................................................................................................... 35
file readable ........................................................................................................................................ 36
file writable ......................................................................................................................................... 36
file type ............................................................................................................................................... 36
File lstat ............................................................................................................................................... 37
file stat ................................................................................................................................................ 37
File System .............................................................................................................................................. 38
file readlink ......................................................................................................................................... 38
file copy ............................................................................................................................................... 38
file rename .......................................................................................................................................... 38
file delete ............................................................................................................................................ 39
file mkdir ............................................................................................................................................. 39
File and Path Names ............................................................................................................................... 39
file dirname ......................................................................................................................................... 39
file extension ....................................................................................................................................... 40
file rootname ...................................................................................................................................... 40
file tail ................................................................................................................................................. 40
file nativename ................................................................................................................................... 40
4
Using {} (braces)
% set name "BillGates"
BillGates
%
% puts {My name is $name}
My name is $name
%
% puts "My name is $name"
My name is BillGates
%
% puts {"My name is $name"}
"My name is $name"
%
% puts "{My name is $name}"
{My name is BillGates}
%
Using [ ] (Brackets)
% set y [set x "def"]
def
%
% puts "X value is : $x"
X value is : def
%
% puts "Y value is : $y"
Y value is : def
%
Math functions
Tcl supports the following mathematical functions in expressions.
abs
acos
asin
atan
atan2
bool
ceil
cos
cosh
double
entier
exp
floor
fmod
hypot
int
isqrt
log
log10
max
min
pow
rand
round
sin
sinh
sqrt
srand
tan
tanh
wide
OPERATORS
The valid operators are listed below, grouped in decreasing order of precedence:
-+~!
Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operators may be applied to string
operands, and bit-wise NOT may be applied only to integers.
*/%
Multiply, divide, remainder. None of these operators may be applied to string operands, and remainder
may be applied only to integers. The remainder will always have the same sign as the divisor and an
absolute value smaller than the divisor.
+Add and subtract. Valid for any numeric operands.
<< >>
Left and right shift. Valid for integer operands only.
&
Bit-wise AND. Valid for integer operands only.
^
Bit-wise exclusive OR. Valid for integer operands only.
|
Bit-wise OR. Valid for integer operands only.
&&
Logical AND. Produces a 1 result if both operands are non-zero, 0 otherwise. Valid for numeric operands
only (integers or floating-point).
||
Logical OR. Produces a 0 result if both operands are zero, 1 otherwise. Valid for numeric operands only
(integers or floating-point).
x?y:z
If-then-else, as in C. If x evaluates to non-zero, then the result is the value of y. Otherwise the result is
the value of z. The x operand must have a numeric value.
% set x 10
10
% set y 15
15
%
% expr $x + $y
25
%
% expr $x * $y
150
%
% expr pow(3,2)
9.0
%
% expr floor(2.345)
2.0
%
% expr ceil(2.999)
3.0
%
Switch command
switch string pattern1 body1 ?pattern2 body2?...?patternN bodyN? ?default?
If no match found it goes to default.
Note: args, patterns or parameters which are mentioned in ?? are the optional.
% set x 10
10
%
% switch $x 10 { puts "X value is : $x" }
X value is : 10
%switch $x {
"10" { puts "X is : $x " }
default { puts "No match found" }
}
X is : 10
%
% switch $x {
abc { puts "abc found" }
default { puts "No match found" }
}
No match found
If command
Syntax : if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?
A simple if command
% if { $x == 10 } {
puts "X values is : 10"
}
X values is : 10
%
If..else command
% if { $x == 15 } {
puts "X values is : 15"
} else {
puts "X values is not equals to 15"
}
X values is not equals to 10
%
If elseif.else command
% if { $x < 10 } {
puts "X value is lessthan 10"
} elseif { $x > 10 } {
puts "X value is greater then 10"
} else {
puts "X value is equals to 10"
}
X value is equals to 10
%
While Loop
% set x 1;
1
%
% while {$x < 5} {
puts "x is $x";
incr x;
---------- incr command used to increment a variable(Default increment value 1.
}
x is 1
x is 2
x is 3
x is 4
%
10
For loop
Synatax :
for
Procedures
Syntax#1 proc name args body
% proc sum {arg1 arg2} {
set x [expr $arg1+$arg2];
return $x
}
%
% puts " The sum of 2 + 3 is: [sum 2 3]"
The sum of 2 + 3 is:5
%
%
Syantax#2
In this case if we miss the argumet, it will take the default value provided in the arguments list.
% proc sum { arg1 {arg2 5} } {
set x [expr $arg1+$arg2];
return $x
}
%
% puts "Sum of 3 and 4 is : [sum 3 4]"
Sum of 3 and 4 is : 7
%
% puts "Sum of 3 and default value is : [sum 3]"
Sum of 2 and default value is : 8
%
11
Global
%set x 5
5
%puts "X value is: $x"
X values is: 5
%
%proc test { } {
puts " X value in side proc is: $x
}
%
%test
can't read "x": no such variable -----proc test is not aware of variable x defined outside the procedure
while executing
"puts "X value is:$x""
(procedure "test" line 2)
invoked from within
"test"
%
% proc test { } {
global x;
-------------------- Declaring 'x' as global variable
incr x;
puts "X value in side proc is: $x"
}
%
% test
X value in side proc is: 6
%
% puts "Now X value is: $x"
Now X value is: 6
%
%
12
Upvar
Syntax : upvar ?level? otherVar1 myVar1 ?otherVar2 myVar2 ...?
Example #1
% proc SetPositive {variable value } {
upvar $variable myvar;
if {$value < 0} { set myvar [expr -$value];} else {set myvar $value;} -- Converting a variabel to +ve value
puts "........ $variable $value myvar : $myvar....."
return $myvar;
}
%
%
% SetPositive x 5;
% SetPositive y -5;
%
%puts "X : $x Y: $y\n"
X : 5 Y: 5
%
% proc two {k} {
upvar 1 $k z ; --------- Giving reference of 'z' in proc one(i.e one level up), to 'z' in this proc.
Now this 'z' gets the value of 'z' in proc one i.e. 5
upvar 2 x a;
--------- Giving reference of 'x' in global space(i.e two levels up), to 'a' in this proc.
Now a gets the value of 'x' i.e. 5
puts "two: Z: $z A: $a";
set z 1; ---------------- Finally this will refer the value 'y' in global space.
set a 2; ---------------- Finally this will refer the value 'x' in global space.
}
%
% proc one {y} {
upvar $y z;
------ Giving reference of 'y' in global space, to z.
Now 'z' gets the value of 'y' i.e. 5
puts "one: Z: $z";
two z;
}
%
% one y;
one: Z: 5
two: Z: 5 A: 5
%
% puts "\nX: $x Y: $y"
X: 2 Y: 1
%
%
13
Example #2
% set x 10;
% set y 15;
%
% proc test { } {
upvar y z;
puts "---- z refers \'y\' value : $z ----"
set z 20; ---------------- This will reflect in 'y' value
test2
}
%
% test
---- z refers 'y' value : 15 ---%
% puts "Now y became : $y"
Now y became : 20
%
%
% proc test2 { } {
upvar 2 x k;
puts "---- k refers \'x\' value : $k ----"
set k 5;
--------------- This will reflect in 'x' value
}
%
% test2
---- k refers 'x' value: 10 ---%
% puts "Now x became : $x"
Now x became : 5
%
%
14
List
Syntax :
list ?arg1 arg2 ...?
set lst {{item 1} {item 2} {item 3}}
set lst [split "item 1.item 2.item 3" "."] ------> split string ?splitChars?
Splits the string into a list of items at splitChars.
set lst [list "item 1" "item 2" "item 3"]
lappend
Syntax: lappend listName ?arg1 arg2 ... argn?
% lappend lst 9 10
%
% puts "$lst"
1 2 3 4 5 6 7 8 9 10 ------------- 9 and 10 appended at the end of the list 'lst'
%
%
linsert
Syntax : linsert list index arg1 ?arg2 ... argn?
% puts "[linsert $lst 3 44]"
1 2 3 44 4 5 6 7 8 9 10
----------- Inserted '44' at index '3' i.e. as a fourth value in the list.
%
%
% set newlst [linsert $lst 3 44]
%
% puts "New list : $newlst"
New list : 1 2 3 44 4 5 6 7 8 9 10
%
% puts "Old list lst is : $lst"
Old list lst is : 1 2 3 4 5 6 7 8 9 10 ------ No change in the original list
%
lreplace
Syntax : lreplace list first last ?arg1 ... argn?
% set newlst [lreplace $lst 2 5 3456] ----- It replaces the 2 to 5 index values with the given numer
%
% puts " New list : $newlst"
New list : 1 2 3456 7 8 9 10
%
%
% puts " Old list : $lst"
Old list : 1 2 3 4 5 6 7 8 9 10
%
%
16
lsearch
Syntax: lsearch list pattern
% set lst "1 2 3 4 5 6 7 8 9 10"
% puts "Value '5' is found at index value: [lsearch $lst 5]" ---- returns the index value of the pattern in
the list, if pattern found
Value '5' is found at index value: 4
%
%
By default, lsearch uses the globbing method of finding a match. Globbing is the wildcarding technique
that the shell uses.
globbing wildcards are:
*
\X
--- The backslash escapes a special character in globbing just the way it does in Tcl substitutions.
Using the backslash lets you use glob to match a * or ?.
[...] --- Matches one occurrence of any character within the brackets. A range of characters can be
matched by using a range between the brackets. For example, [a-z] will match any lower case
letter.
% set list "{Washington 1789} {Adams 1797} {Jefferson 1801} {Madison 1809} {Monroe 1817} {Adams
1825}"
%
% puts "Jefferson is found at index : [lsearch $list Jefferson*]"
Jefferson is found at index : 2
%
% puts "Madison is found at index : [lsearch $list *diso*]"
Madison is found at index : 3
%
%
lsort
Syntax : lsort -option list
Options are,
-dictionary : Dictionary order (2 comes before 10, a comes before B, etc)
-decreasing : Largest items first
% set lst " 5 3 1 2 02 001 10 7 6 4 9 8"
%
% puts [lsort $lst]
001 02 1 10 2 3 4 5 6 7 8 9
17
%
% puts [lsort -decreasing $lst]
9 8 7 6 5 4 3 2 10 1 02 001
%
% puts [lsort -dictionary $lst]
1 001 2 02 3 4 5 6 7 8 9 10
%
lrange
Syntax : lrange list first last
% set lst "1 2 3 4 5 6 7 8 9 10"
%
% puts [lrange $lst 3 7]
45678
%
%
concat
Syntax: concat ?arg1 arg2 ... argn?
% set list1 "1 2 3 4 5"
12345
%
% set list2 "a b c d e"
abcde
%
%
% set list3 [concat $list1 $list2]
12345abcde
%
%
% puts "Now list3 is : $list3"
Now list3 is : 1 2 3 4 5 a b c d e
%
%
18
String command
string length
Syntax: string length string
Returns the length of string
% set string "this is my test string"
%
% puts "Length of the string is : [string length $string]"
Length of the string is : 22
%
%
string index
Syntax:
string index string index
Returns the char at the given index position in string.
% set string "My Name Is Surya"
%
% puts "[string index $string 3] is the second character in \"$string\""
N is the second character in "My Name Is Surya"
%
%
string range
Syntax: string range string first last
Returns a string composed of the characters from first to last
% set string "this is my test string"
%
% puts "\"[string range $string 5 10]\" are characters between the 5'th and 10'th"
"is my " are characters between the 5'th and 10'th
%
%
string compare
Syntax: string compare string1 string2
Compares string1 to string2 and returns
*
-1 ..... If string1 is less than string2
*
0 ........ If string1 is equal to string2
*
1 ........ If string1 is greater than string2 These comparisons are done lexicographically,
not numerically.
19
Searches for string1 in string2 from the last. Returns index value if string1 found in string2. Other wise
returns -1.
20
% puts [string last "is" "my name is surya, this is test message" ]
23 --------------- 'is' found at 8th, 20th and 23 rd positions. But it returns last match.
%
% puts [string last "is" "my name is surya, this is test message" 20]
8
--------------- it starts searching for 'is' from index value '20' to the start index.
%
string wordstart
Syntax: string wordstart string index
Searches for the starting of word after the given index value.
% puts [string wordstart "hello world test message" 0]
0 ----- It searches for the word 'tcl' towards start of the sting from the given index '0' and the word
found at 0'th position and returned '0'
%
% puts [string wordstart "hello world test message" 8]
6 ----- It searches for the nearest word before index '8' and found a word started at index '6'
%
% puts [string wordstart "hello world test message" 20]
17 ----- Before index '20', a word started at index '17'
%
string wordend
Syntax: string wordend string index
Searches for the word end after the given index value.
% puts [string wordend "hello world test message" 0]
5
----- After starting from the given index '0' a word end found at '5'th index.
%
% puts [string wordend "hello world test message" 12]
16
----- After starting from the given index '12'th pisition, a word end found at 16th position.
%
string match
Syntax: string match ?-nocase? pattern string
% puts [string match "*ampl*" "this is sample message"]
1
--- found pattern "*ampl* at "sample"
%
21
string tolower
Syntax: string tolower string ------ Convert a string/word to lower case
% puts [string tolower "HELLO WORLD"]
hello world
string toupper
Syntax: string toupper string ------ Convert a string/word to upper case
% puts [string tolower " hello world "]
HELLO WORLD
%
string totitle
Syntax: string totitle string ------ Convert first letter of the stirng/word to Upper case
% puts [string totitle " hello world "]
Hello world
string trim
Syntax: string trim string ?trimChars?
trimChars removed from both ends. By default trimChars are whitespace (spaces, tabs, newlines)
% puts [string trim " hello world "]
hello world
%
% puts [string trim "hi ---- hello world-------- hello world----%
string trimleft
Syntax: string trimleft
hi" hi]
string ?trimChars?
trimChars removed from the left. By default trimChars are whitespace (spaces, tabs, newlines)
% puts [string trimleft " hello world " ]
hello world
%
% puts [string trimleft "hello world" he]
llo world
22
string trimright
Syntax: string trimtrim
string ?trimChars?
trimChars removed from the right. By default trimChars are whitespace (spaces, tabs, newlines)
% puts [string trimright " hello world " ]
hello world
%
% puts [string trimright "hello world" rld]
hello wo
format
Syntax: format
Cost
30 Cents Each
20 Cents Each
10 Cents Each
3.60 per Lb.
23
regexp
Syntax:
[...]
[^...] ----- Matches any character *NOT* a member of the set of characters following the ^.
(...)
Example :
set sample "Where there is a will, There is a way."
set result [regexp {[a-z]+} $sample match]
puts "Result: $result match: $match"
set result [regexp {([A-Za-z]+) +([a-z]+)} $sample match sub1 sub2 ]
puts "Result: $result Match: $match 1: $sub1 2: $sub2"
Output:
Result: 1 match: here
Result: 1 Match: Where there 1: Where 2: there
[0-9]+ or \d+ matches any numeric string.
[a-z]+ matches any lowercase word
[A-Z]+ matches any uppercase words
\s+ matches any number of spaces
[a-zA-z0-9] matches any alpha-numberic word with any case
24
regsub
Syntax: regsub ?switches? exp string subSpec varName
Searches string for substrings that match the regular expression exp and replaces them with subSpec.
set sample "Where there is a will, There is a way."
regsub "way" $sample "lawsuit" sample2
puts "New: $sample2"
Output:
New: Where there is a will, There is a lawsuit.
Array
We can define arrays in three types.
1) array set array1 [list {123} {Abigail Aardvark} {234} {Bob Baboon} {345} {Cathy Coyote}]
2) array set array1 { {123} {Abigail Aardvark} {234} {Bob Baboon} {345} {Cathy Coyote} }
3) set array1(123) "Abigail Aardvark"
set array1(234) "Bob Baboon"
set array1(345) "Cathy Coyote"
% puts $array1(234)
Bob Baboon
%
array exists
Syntax: array exists arrayName
Returns 1 if arrayName is an array variable. Returns 0 if arrayName is a scalar variable, proc, or does not
exist.
% if {[array exist array1]} {
puts "array1 is an array"
} else {
puts "array1 is not an array"
}
array1 is an array
%
25
array names
Syntax: array names arrayName ?pattern
Returns a list of the indices for the associative array arrayName. If pattern is supplied, only those indices
that match pattern are returned.
% puts "Array1 has the following entries: \n [array names array1] \n"
345 234 123
array size
Syntax: array size arrayName
Returns the number of elements in array arrayName.
%puts "Size of the array1 is: [array size array1]"
3
%
array get
Syntax: array get arrayName
% puts [array get array1]
345 {Cathy Coyote} 234 {Bob Baboon} 123 {Abigail Aardvark}
%
array set
Syntax: array set arrayName
dataList
26
There are two methods for iterating through the contents of an associative array.
Using a foreach loop with the output from the array names command
Method#1
% foreach id [array names array1] {
puts "$array1($id) has ID: $id"
}
Cathy Coyote has ID: 345
Bob Baboon has ID: 234
Abigail Aardvark has ID: 123
hello world has ID: 456
Method #2
array startsearch
Syntax: array startsearch arrayName
Initializes arrayName for use with the iterating commands, and returns the searchID token that must be
passed to those commands.
% puts [array startsearch array1]
s-1-array1
------- searchID
%
array nextelement
Syntax: array nextelement
arrayName searchID
Returns the index of the next element in arrayName. If there are no more elements in arrayName, then
an empty string is returned.
% puts [array startsearch array1]
s-1-array1
% puts [array nextelement array1 s-1-array1]
345
% puts [array nextelement array1 s-1-array1]
234
% puts [array nextelement array1 s-1-array1]
123
% puts [array nextelement array1 s-1-array1]
456
% puts [array nextelement array1 s-1-array1] ----- no elements in array to show
%
27
array anymore
Syantax: array anymore arrayName searchID
Returns a 1 if there are still elements in arrayName to be returned by nextelement. Otherwise, it returns
0.
% puts [array startsearch array1]
s-1-array1
%
% puts [array anymore array1 s-1-array1]
1
% puts [array nextelement array1 s-1-array1]
345
% puts [array anymore array1 s-1-array1]
1
% puts [array nextelement array1 s-1-array1]
234
% puts [array anymore array1 s-1-array1]
1
% puts [array nextelement array1 s-1-array1]
123
% puts [array anymore array1 s-1-array1]
1
% puts [array nextelement array1 s-1-array1]
456
% puts [array anymore array1 s-1-array1]
0 --------- There are no elements in the array
array donesearch
Syntax: array donesearch
arrayName searchID
Destroys the state information associated with the iteration commands. This command should be
executed when an iteration is complete.
% puts [array startsearch array1]
s-1-array1
%
% puts [array anymore array1 s-1-array1]
1
% puts [array donesearch array1 s-1-array1]
%
% puts [array anymore array1 s-1-array1]
-------couldn't find search "s-1-array1" ------ searchID got destroyed
while executing
"array anymore array1 s-1-array1"
28
Accessing Files
Tcl supports an interface to the file system using the buffered i/o mechanism.
Open
Syntax: open fileName ?access? ?permission?
Opens a file and returns a token to be used when accessing the file.
*
permission is an integer to use to set the file access permissions. The default is rw-rw-rw(0666).
Close
Syntax: close fileID
Closes a file previously opened with open, and flushes any remaining output.
Gets
Synatx: gets fileID ?varName?
Reads a line of input from FileID.
If there is a varName argument, gets returns the number of characters read (or -1 if an EOF occurs), and
places the line of input in varName.
29
Puts
Synatx:
Writes the characters in string to the stream referenced by fileID(writes at the end).
FileID is one of:
*
The value returned by a previous call to open with write access.
*
stdout
*
stderr
Read
Syntax#1 read ?-nonewline? fileID
Reads all the remaining bytes from fileID, and returns that string. If -nonewline is set, then the last
character will be discarded if it is a newline. Any existing end of file condition is cleared before the read
command is executed.
Syntax#2 read
fileID
numBytes
Reads up to numBytes from fileID, and returns the input as a Tcl string. Any existing end of file condition
is cleared before the read command is executed.
Seek
Syntax:
Change the current position within the file referenced by fileID. Note that if the file was opened with
"a" access that the current position can not be set before the end of the file for writing, but can be set to
the beginning of the file for reading.
*
*
offset is the offset in bytes at which the current position is to be set. The position from which
the offset is measured defaults to the start of the file, but can be from the current location, or the end
by setting origin appropriately.
*
origin is the position to measure offset from. It defaults to the start of the file. Origin must be
one of:
=
start.........Offset is measured from the start of the file.
=
current...Offset is measured from the current position in the file.
=
end...........Offset is measured from the end of the file.
30
tell
Syntax: tell fileID
Returns the position of the access pointer in fileID as a decimal string.
flush
Syntax: flush fileID
Flushes any output that has been buffered for fileID.
eof
Syntax: eof fileID
returns 1 if an End Of File condition exists, otherwise returns 0.
Examples:
% cat myfile
This is line1
This is line2
This is line3
This is line4
%
% open myfile r
file5
%
% gets file5 ------- gets reads only one line
This is line1
%
% gets file5
This is line2
%
% read file5 ------- read reads remaining
This is line3
This is line4
%
%
% read file5 ----- nothing to read
%
% close file5 ----- closing the previously opened file
31
% cat myfile
This is line1
This is line2
This is line3
This is line4
%
% open myfile r
file5
%
% read file5 10 ----- reads only 10bytes
This is li
%
% gets file5
------ get the current position to end of the line
ne1
%
% gets file5
This is line2
%
% seek file5 0 start ---- seek the position to the 0th byte from the start of the file
% gets file5
This is line1
%
% seek file5 5 start --- seek the position to the 5th byte from the start of the file
% gets file5 ------ gets the current position to the end of the line
is line1
%
% tell file5 ---- returns the position number
14
%
% close file5
%
32
% cat myfile
This is line1
This is line2
This is line3
This is line4
%
%
%
% open myfile a ----- Opening a file for appedning
file5
%
% puts file5 "This appends at the end of the file"
% close file5
%
%
% cat myfile
This is line1
This is line2
This is line3
This is line4
This appends at the end of the file ---- New line appended at the end
%
%
Glob
Syntax:
----
Allows glob to return an empty list without causing an error. Without this flag, an
error would be generated when the empty list was returned.
----- This is default
Pattern follows the same matching rules as the string match globbing rule
% glob /root/myfile
----- Returned the file
/root/myfile
%
% glob /root/myfile1 ----- Thrown an error as the file doesnt exists
no files matched glob pattern "/root/myfile1"
%
% glob -nocomplain /root/myfile1
------- Doesnt thrown any error even the file was not exists
%
33
File status
file size
Syntax: file size name
Returns the size of name in bytes.
% % file size myfile
92
%
file atime
Syntax: file atime name
Returns the number of seconds since 1/1/1970 when the file name was last accessed. Generates an
error if the file doesn't exist.
% file atime myfile
1335162779
%
file mtime
Syntax: file mtime name
Returns the time of the last data modification in seconds since Jan 1, 1970.
% file mtime myfile
1335162776
%
file exists
Syntax: file exists name
Returns a 1 if the file name exists, and the user has search access in all the directories leading to the file.
Otherwise, a 0 is returned.
% file exists myfile
1
%
% file exists nofile
0
%
34
File isdirectory
Syntax : file isdirectory name
Returns 1 if file name is a directory, otherwise returns 0.
% mkdir mydir
%
% file isdirectory mydir
1
%
% file isdirectory not-a-dir
0
file isfile
Syntax: file isfile name
Returns 1 if file name is a regular file, otherwise returns 0.
% touch newfile
%
% file isfile newfile
1
% file isfile nofile
0
%
file owned
Syntax: file owned name
Returns 1 if the file is owned by the current user, otherwise returns 0.
% file owned myfile
1
% % file owned /home/testuser/testfile
0
%
file executable
Syntax: file executable name
Returns a 1 if file has execute permissions to the current user, otherwise returns a 0.
% ls -l myfile
-rw-r--r-- 1 root root 92 Apr 23 12:02 myfile
%
% file executable myfile
0
% chmod 755 myfile
%
% ls -l myfile
-rwxr-xr-x 1 root root 92 Apr 23 12:02 myfile
%
% file executable myfile
1
35
file readable
Syntax: file readable name
Returns 1 if it has read permissions to the current user, otherwise returns 0.
% ls -l myfile
-rw-r--r-- 1 root root 92 Apr 23 12:02 myfile
%
% file readable myfile
1
%
file writable
Syntax: file writable name
Returns 1 if file has write permissions to the current user, otherwise returns 0.
% file writable myfile
1
%
file type
Syntax: file type name
Returns a string giving the type of file name, which will be one of:
*
file...................................Normal file
*
directory........................Directory
*
characterSpecial.......Character oriented device
*
blockSpecial.............. Block oriented device
*
fifo...................................Named pipe
*
link..................................Symbolic link
*
socket............................Named socket
% file type myfile
file
%
% file type mydir
directory
%
36
File lstat
Syntax: file lstat name varName
This returns the same information returned by the system call lstat. The results are placed in the
associative array varName. The indexes in varName are:
*
atime.......time of last access
*
ctime.......time of last file status change
*
dev...........inode's device
*
gid............group ID of the file's group
*
ino............inode's number
*
mode.......inode protection mode
*
mtime.....time of last data modification
*
nlink........number of hard links
*
size...........file size, in bytes
*
type..........Type of File
*
uid.............user ID of the file's owner Because this calls lstat, if name is a symbolic link,
the values in varName will refer to the link, not the file that is linked to.
file stat
Syntax: file stat name varName
This returns the same information returned by the system call stat. The results are placed in the
associative array varName. The indexes in varName are:
*
atime.......time of last access
*
ctime.......time of last file status change
*
dev...........inode's device
*
gid............group ID of the file's group
*
ino............inode's number
*
mode.......inode protection mode
*
mtime.....time of last data modification
*
nlink........number of hard links
*
size...........file size, in bytes
*
type..........Type of File
*
uid.............user ID of the file's owner
37
File System
file readlink
Syntax: file readlink name
Returns the name of the file a symlink is pointing to. If name isn't a symlink, or can't be read, an error is
generated.
% file readlink myfile
could not readlink "myfile": invalid argument
%
% ln -s myfile linkfile
%
% file readlink linkfile
myfile
%
file copy
Syntax: file copy ?--force? sourcePath targetPath
Copies a file from the source path to the target. Will not overwrite a file unless the --force option is
provided.
% file copy myfile myfile1
%
% file copy myfile myfile1
error copying "myfile" to "myfile1": file already exists
%
% file copy -force myfile myfile1
%
file rename
Syntax: file rename ?--force? sourcePath targetPath
Moves a file from the source path to the target. Will not overwrite a file unless the --force option is
provided.
% ls
myfile myfile1
%
% file rename myfile myfile2
%
% file rename myfile1 myfile2
error renaming "myfile1" to "myfile2": file already exists
%
% file rename -force myfile1 myfile2
% ls
myfile2
%
38
file delete
Syntax: file delete ?--force? path
Deletes a file or directory from the filesystem.
% ls
mydir myfile2
%
% file delete myfile2
%
% ls
mydir
%
file mkdir
Syntax: file mkdir ?--force? path
Creates a new folder.
% ls
myfile
%
% file mkdir mydir
%
% ls
mydir myfile
%
39
file extension
Syntax: file extension name
Returns the file extension.
% file extension test.sh
.sh
%
% file extension test.tcl
.tcl
%
file rootname
Syntax: file rootname name
Returns all of the characters in name up to but not including the last . character in the last component
of name. If the last component of name does not contain a dot, then returns name.
% file rootname /root/test.dir/test.dir
/root/test.dir/test
%
% file rootname /home/testuser/testdir
/home/testuser/testdir
%
file tail
Syntax: file tail name
Returns all of the characters in name after the last slash. Returns $name if name contains no slashes.
% file tail /root/Desktop/mydir/myfile
myfile
%
file nativename
Syntax: file nativename path
Returns the native name of a file. Useful when using exec to invoke a platform-native application that
requires a pathname in the platform's format.
40
file normalize
Syntax: file normalize path
Returns an absolute path without any "../", or "./" components.
% ls ../myfile
../myfile
%
% file normalize ../myfile
/root/myfile
------------ returns full path
%
file split
Syntax: file split path
Splits a path into a list in which each list element is a folder name the last element may be a file name.
% file split /home/testuser/testdir/testfile
/ home testuser testdir testfile
%
file join
Syntax: file join list
Converts a list of folders into a platform-native file path.
% file join / home testuser testdir testfile
/home/testuser/testdir/testfile
%
% file join home testuser testdir testfile
home/testuser/testdir/testfile
%
file attributes
Syntax#1 file attributes name
% file attributes myfile
-group root -owner root -permissions 00644
%
Syntax#2 file attributes name ?option?
% file attributes myfile -group
root
%
% file attributes myfile -permissions
00644
%
41
42
file separator
Syntax:
file
separator ?name?
If no argument is given, returns the character which is used to separate path segments for native files on
this platform.
% file separator
/
%
If a path is given, the filesystem responsible for that path is asked to return its separator character. If no
file system accepts name, an error is generated.
file system
Syntax: file system name
% file system /dev/hda2
native
%
file volumes
Syntax: file volumes
Returns the absolute paths to the volumes mounted on the system, as a proper Tcl list. Without any
virtual filesystems mounted as root volumes, on UNIX, the command will always return /, since all
filesystems are locally mounted.
% file volumes
/
%
In Windows:
puts [file volumes]
A:/ C:/ D:/ M:/
Exec
Syntax: exec ?switches? arg1 ?arg2? ... ?argN? --- switch values are -keepnewline and --
% set a [exec ls]
mydir
myfile
test.sh
%
% puts $a
mydir
myfile
test.sh
%
43
Info Commands
Syntax: info option ?arg arg ...?
info args
Syntax: info args procname
Returns a list containing the names of the arguments to procedure procname, in order. Procname must
be the name of a Tcl command procedure.
% proc add { arg1 arg2} {
return [expr $arg1+$arg2]
}
%
% info args add
arg1 arg2
%
info body
Syntax: info body procname
Returns the body of procedure procname. Procname must be the name of a Tcl command procedure
% info body add
return [expr $arg1+$arg2]
%
info cmdcount
Syntax: info cmdcount
Returns a count of the total number of commands that have been invoked in this interpreter.
% info cmdcount
358
% info cmdcount
366
%
44
info commands
Syntax: info commands ?pattern?
If pattern isn't specified, returns a list of names of all the Tcl commands in the current namespace,
including both the built-in commands written in C and the command procedures defined using the proc
command.
If pattern is specified, only those names matching pattern are returned.
% info commands
tell socket subst open eof pwd glob list exec pid auto_load_index time unknown eval lrange fblocked
lsearch auto_import gets case lappend proc break variable llength auto_execok return linsert error catch
clock info split array if fconfigure concat join lreplace add source fcopy global switch auto_qualify
update close cd for auto_load file append format read package set binary namespace scan trace seek
while flush after vwait uplevel continue foreach lset rename fileevent regexp upvar unset encoding expr
load regsub history interp exit puts incr lindex lsort tclLog string
%
%
% info commands a*
auto_load_index auto_import auto_execok array add auto_qualify auto_load append after
%
In the above output add is defined by us in the previous step.
info exists
Syntax: info exists varName
Returns 1 if the variable named varName exists in the current context (either as a global or local
variable), returns 0 otherwise.
% info exists var
0
%
% set var 10
10
%
% info exists var
1
%
info complete
Syantax: info comlete string
If string has no unmatched brackets, braces or parentheses, then a value of 1 is returned, else 0 is
returned.
% set cmd { puts "hello world}
% info complete $cmd
0
% set cmd { puts "hello world}; info complete $cmd; --------> Returns 1
45
info globals
Syntax: info globals ?pattern?
If pattern isn't specified, returns a list of all the names of currently-defined global variables. Global
variables are variables in the global namespace. If pattern is specified, only those names
matchingpattern are returned.
% set var 10
10
% % set a 5
5
% proc test { } {
global a
return $a
}
%
% info globals
tcl_rcFileName tcl_version argv0 argv tcl_interactive a var auto_oldpath errorCode auto_path errorInfo
auto_index env tcl_pkgPath tcl_patchLevel argc tcl_libPath tcl_library tcl_platform
%
info hostname
Syntax: info hostname
Returns the name of the computer on which this invocation is being executed.
% info hostname
localhost
%
info library
Syntax: info library
Returns the name of the library directory in which standard Tcl scripts are stored.
% info library
/usr/share/tcl8.4
%
info nameofexecutable
Syntax: info nameofexecutable
Returns the full path name of the binary file from which the application was invoked.
% info nameofexecutable
/usr/bin/tclsh
%
46
info patchlevel
info patchlevel
Returns the value of the global variable tcl_patchLevel
% info patchlevel
8.4.13
%
info procs
Syntax: info procs ?pattern?
Returns a list of all the names of Tcl command procedures in the current namespace.
% info procs
auto_load_index test unknown auto_import auto_execok add auto_qualify auto_load history tclLog
%
% info procs t*
test tclLog
%
info script
Syntax: info script
If a Tcl script file is currently being evaluated.
info sharedlibextension
Syntax: info sharedlibextension
Returns the extension used on this platform for the names of files containing shared libraries.
% info sharedlibextension
.so
%
info tclversion
Syntax: info tclversion
Returns the value of the global variable tcl_version
% info tclversion
8.4
%
info vars
Syntax: info vars ?pattern?
Returns a list of all the names of currently-visible variables.
% info vars
tcl_rcFileName tcl_version argv0 argv tcl_interactive a var b auto_oldpath errorCode auto_path
errorInfo auto_execs auto_index env tcl_pkgPath tcl_patchLevel argc tcl_libPath tcl_library tcl_platform
%
% info vars a*
argv0 argv a auto_oldpath auto_path auto_execs auto_index argc
47
Source command
Syntax: source filename
The source command will load a file and execute it.
This command can be used to:
make a library file that contains all the procs for a particular set of functions.
configure programs
Package Commands
Tcl supports grouping multiple procedures or compiled "C" code modules into a single entity referred to
as a package. A package may consist of a single file, multiple files or a mix of compiled and Tcl script
files.
To access a package from a script:
1
Make certain that the auto_path global variable includes the path to the package you
wish to include. The standard Tcl distributions include the proper paths by default.
2
Include a line like this in the application that uses a package:
package require nameOfPackage
You script will need a separate package require command for each package you wish to include.
To create a package, you'll need
1
to include a package provide command like
package provide nameOfPackage revisionNumber
in each file that's included in the package
2
create a pkgIndex.tcl file to describe the files in the package.
This can be done with the pkg_mkIndex command.
48
package provide
Syntax: package provide name revision
Declares that this file provides an implementation of a specific revision of a package. A file may include
only one package provide command.
%
% cat myfile.tcl
package provide demopkg 1.0
proc demoproc {} {
puts "Running the demoproc"
}
proc add { a b } {
set c [expr $a + $b]
return $c
}
%
pkg_mkIndex
Syntax: pkg_mkIndex libdir file1 ... filen
Creates an index file (pkgIndex.tcl) in libdir from the source code modules listed as file1 - filen. Each proc
in the files will be listed in the index file, with a reference to the source code module that contains it.
% pkg_mkIndex /root/mydir myfile.tcl
%
package require
Syntax: package require name ?revision?
Tells the interpreter to find a package with the given name and optional revision number. If the revision
number is absent, the largest revision available is used.
% add 2 3
invalid command name "add"
%
% lappend auto_path /root/mydir
/usr/share/tcl8.4 /usr/share /usr/lib /root/mydir
%
% package require demopkg
1.0
%
% add 2 3
5
%
49
Eval Command
Syntax:
Evaluates arg1 - argn as one or more Tcl commands. The args are concatenated into a string, and
passed to tcl_Eval to evaluate and execute.
Eval returns the result (or error code) of that evaluation.
The eval command will evaluate a list of strings as though they were commands typed at the % prompt
or sourced from a file.
50
Subst Command
Syntax: subst ?-nobackslashes? ?-nocommands? ?-novariables? String
If any of the -no... arguments are present, then that set of substitutions will not be done.
The Tcl interpreter does only one substitution pass during command evaluation. Some situations, such
as placing the name of a variable in a variable, require two passes through the substitution phase. In this
case, the subst command is useful.
Subst performs a substitution pass without performing any execution of commands except those
required for the substitution to occur, ie: commands within [] will be executed, and the results placed in
the return string.
% set a 1
1
% set c a
a
%
% puts $$c
$a
%
% puts [subst $$c]
1
%
% puts "format with no subst [format {$%s} $c]"
format with no subst $a
%
% puts "format with subst: [subst [format {$%s} $c]]"
format with subst: 1
%
% set a arrayname
% set b index
% set c newvalue
% eval [format "set %s(%s) %s" $a $b $c]
% puts "Index: $b of $a was set to: $arrayname(index)"
Index: index of arrayname was set to: newvalue
51
52