Command line arguments and environment strings

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 that extracts a particular value from a file could be written so that it prompts for a file name, reads the file name, and then extracts the data. Or, it could be written to loop through as many files as are in the command line, and extract the data from each file, and print the file name and data.

The second method of writing the program can easily be used from other scripts. This makes it more useful.

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.


Example

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)"
}