Passing Arguments from command line into a TCL Script

Items of data passed to a script from the command line are known as arguments. For example, take the simple script presented in using the command line tutorial. 
puts [expr 10 + 20]
 
Lets assume the script has been saved as add.exp and that the present working directory of the shell window in which we are working matches the directory in which the script has been saved. We know the script can be run using the following command,
./add.exp

Of course the output is always the same because the values being added are hard-coded into the script. The script would be more useful if we could pass values to the script from the command line. 
./add.exp 10 20

The method by which numbers can be passed into, and used by a script, is as follows.

argc argv argv0
All Tcl scripts have access to three predefined variables.
    $argc - number items of arguments passed to a script.
    $argv - list of the arguments.
    $argv0 - name of the script.


To use the arguments, the script could be re-written as follows.


if { $argc != 2 } {
        puts "The add.exp script requires two numbers as input."
                puts "For example, ./add.exp 10 20".
                puts "Please try again."
} else {
        puts [expr [lindex $argv 0] + [lindex $argv 1]]
}


The lindex command returns the first and second items from the list of arguments entered at the command line. Items in a list are counted from zero.

No comments:

Post a Comment