Tcl Tutorial Lesson 38

Command line arguments and environment strings

Scripts are much more useful if they can be called with different values in the command line.

For instance, a script may extract a particular value from a file by first asking for the name of the file, then reading the file name, and then extracting the data from that file.

An alternative is to use the arguments on the command-line: the script can then loop through all the files given there, and extract the data from each file.

The second method of writing the program can easily be used from other scripts. This is actually a very powerful method.

The number of command line arguments to a Tcl script is passed as the global variable argc. The name of a Tcl script is passed to the script as the global variable argv0, and the rest of the command line arguments are passed as a list in argv. The name of the executable that runs the script, such as tclsh is given by the command info nameofexecutable

Another method of passing information to a script is with environment variables. For instance, suppose you are writing a program in which a user provides some sort of comment to go into a record. It would be friendly to allow the user to edit their comments in their favorite editor. If the user has defined an EDITOR environment variable, then you can invoke that editor for them to use.

Environment variables are available to Tcl scripts in a global associative array env. The index into env is the name of the environment variable. The command puts "$env(PATH)" would print the contents of the PATH environment variable.


puts "There are $argc arguments to this script"
puts "The name of this script is $argv0"
if {$argc > 0} {puts "The other arguments are: $argv" }

puts "You have these environment variables set:"
foreach index [array names env] {
    puts "$index: $env($index)"