How to Use Command Line Arguments in Tcl

Tcl programs can accept command line arguments to pass runtime variables. These code examples show how to make use of these arguments. A couple special variables are provided: $argv and $argc. One holds the values passed, and the other holds the count of arguments. Can you guess which one is which?


# $argc contains the number of command
# line arguments supplied by the user

# When running either of these, $argc will be 0
tclsh myScript.tcl

# When running this, $argc will be 2
tclsh myScript.tcl Hello world


# $argv is a list of all the argument values

# Print as single string
puts $argv

# Iterate through each value and print on separate lines
foreach argValue $argv {
   puts $argValue

# Access a specific element (zero-based index)
puts [lindex $argv 0] # First
puts [lindex $argv 1] # Second