ZetCode

Tcl command-line arguments

last modified November 24, 2026 Tcl 8.6

A Tcl script receives its command-line arguments in two global variables: argv holds the arguments as a list and argc holds their number. A third variable, argv0, holds the name of the script as it was invoked. There is no option parser in the core interpreter, so the script itself decides which words are flags, which take values and which are file names.

The examples build a small command-line tool step by step: first printing the arguments, then taking two positional names, then adding flags, options with values, the -- terminator, a usage message with a meaningful exit status, and finally reading records from standard input.

argv, argc and argv0

argv is an ordinary Tcl list, so list commands work on it directly. argc is the length of that list, provided for convenience. Note that the script name is not part of argv; it is available separately in argv0. The first script prints all three.

args.tcl
puts "argv0: [file tail $argv0]"
puts "argc:  $argc"
puts "argv:  $argv"

foreach arg $argv {
    puts "- $arg"
}

The script was called with three arguments, one of which contains a space. Tcl passes every shell word as one list element, so the quoted argument stays together. Printing the list with puts adds braces around the element with a space, while foreach shows the elements one per line without braces. file tail strips the directory from argv0, which is useful in messages.

$ tclsh args.tcl alpha beta "two words"
argv0: args.tcl
argc:  3
argv:  alpha beta {two words}
- alpha
- beta
- two words

Positional arguments

A script that takes a fixed number of names should check argc before reading them. lassign copies list elements into variables in one step and is clearer than repeated lindex calls. If the count is wrong, print a usage line and exit with a nonzero status.

positional.tcl
if {$argc != 2} {
    puts "usage: tclsh positional.tcl SOURCE DEST"
    exit 1
}

lassign $argv source dest

puts "copying $source to $dest"
puts "source name: [file tail $source]"
puts "dest name:   [file tail $dest]"
puts "extension:   [file extension $dest]"

With two arguments the script takes the normal path and describes the copy it would perform. With one argument it prints the usage line and exits with status 1, which tells a shell script or a build tool that the command failed. The script does not actually copy anything; the names are only inspected with file tail and file extension, which the Tcl files and directories article explains in detail.

$ tclsh positional.tcl report.txt backup.txt
copying report.txt to backup.txt
source name: report.txt
dest name:   backup.txt
extension:   .txt
$ tclsh positional.tcl report.txt; echo "exit: $?"
usage: tclsh positional.tcl SOURCE DEST
exit: 1

A simple flag loop with --help

Flags are words that change the behaviour of the program and carry no value. A foreach loop over argv with a switch handles them. The double dash after switch ends the options of switch itself, so patterns beginning with a dash are treated as patterns and not as switch options.

flags.tcl
set verbose 0
set files {}

foreach arg $argv {
    switch -- $arg {
        --help {
            puts "usage: list.tcl \[--verbose\] \[--help\] FILE..."
            exit 0
        }
        --verbose {
            set verbose 1
        }
        default {
            lappend files $arg
        }
    }
}

if {$verbose} {
    puts "verbose mode, [llength $files] file(s)"
}
foreach file $files {
    puts "processing $file"
}

The default branch treats every unrecognized word as a file name, which is a common and forgiving design for a filter command. --help prints the usage text and exits immediately with status 0, because asking for help is not an error. The square brackets in the usage string are escaped so that Tcl prints them instead of trying a command substitution. The Tcl exit command page covers the status argument.

$ tclsh flags.tcl --verbose a.txt b.txt
verbose mode, 2 file(s)
processing a.txt
processing b.txt
$ tclsh flags.tcl --help; echo "exit: $?"
usage: list.tcl [--verbose] [--help] FILE...
exit: 0

Handling options with values

An option such as --port 9090 consumes two words. The loop needs an index instead of foreach, because after reading an option the script must skip its value. incr i advances the index, and a check before lindex catches a missing value at the end of the list.

options.tcl
set host localhost
set port 8080
set name {}

for {set i 0} {$i < $argc} {incr i} {
    set option [lindex $argv $i]
    switch -- $option {
        --host - --port - --name {
            incr i
            if {$i >= $argc} {
                puts "missing value for $option"
                exit 2
            }
            set value [lindex $argv $i]
            switch -- $option {
                --host { set host $value }
                --port { set port $value }
                --name { set name $value }
            }
        }
        default {
            puts "unknown option: $option"
            exit 2
        }
    }
}

puts "host=$host port=$port name=$name"

The three option names share one branch. A body consisting of a single dash means "use the next body", so --host and --port fall through to the code that reads a value. The inner switch then assigns the value to the right variable. Defaults are set before the loop, so omitted options keep their initial values. An unknown option or a missing value ends the program with status 2, which distinguishes a usage error from the status 1 used for a failed operation.

$ tclsh options.tcl --host example.com --port 9090 --name "web server"
host=example.com port=9090 name=web server
$ tclsh options.tcl --host; echo "exit: $?"
missing value for --host
exit: 2

The -- terminator

A file called -strange.txt looks exactly like a flag. The usual convention is a bare --: everything after it is an operand, even when it starts with a dash. The parser keeps a boolean that switches to operand mode when the terminator is seen.

terminator.tcl
set files {}
set after_terminator 0

foreach arg $argv {
    if {$after_terminator} {
        lappend files $arg
        continue
    }
    if {$arg eq "--"} {
        set after_terminator 1
        continue
    }
    if {[string match -* $arg]} {
        puts "option: $arg"
    } else {
        lappend files $arg
    }
}

puts "files: $files"

The loop handles three cases in order: after the terminator everything is a file, the terminator itself is consumed, and a leading dash marks an option. string match -* is a glob match, not a regular expression, which is enough for this test. In the run below, -v is the only option; --verbose comes after -- and is therefore a file name, even though it has the same shape as a flag.

$ tclsh terminator.tcl -v -- -strange.txt --verbose
option: -v
files: -strange.txt --verbose

Usage messages and exit status

A usage message belongs on standard error, not on standard output, so that it does not mix with the real result when the output is redirected. The status should be 0 for success, 1 for a runtime failure and 2 for a usage error; the exact numbers are a convention, but keeping them consistent makes the script usable from a shell. The next program combines the previous techniques.

usage.tcl
proc usage {} {
    puts stderr "usage: convert.tcl -i INPUT -o OUTPUT"
    puts stderr "  -i  input file"
    puts stderr "  -o  output file"
}

proc fail {message} {
    puts stderr "error: $message"
    usage
    exit 2
}

set input {}
set output {}

for {set i 0} {$i < $argc} {incr i} {
    set option [lindex $argv $i]
    switch -- $option {
        -i - -o {
            incr i
            if {$i >= $argc} {
                fail "missing value for $option"
            }
            set value [lindex $argv $i]
            if {$option eq "-i"} {
                set input $value
            } else {
                set output $value
            }
        }
        default {
            fail "unknown option: $option"
        }
    }
}

if {$input eq "" || $output eq ""} {
    fail "both -i and -o are required"
}

puts "converting $input to $output"

The fail procedure centralizes the error path: it prints the reason, prints the usage text and exits with status 2. Required options are checked after parsing, so a missing -o produces one clear message instead of a confusing empty file name. The success path prints a normal line to standard output. In the output below, the shell's $? shows the status that the parent process receives.

$ tclsh usage.tcl -i report.txt -o report.csv
converting report.txt to report.csv
$ tclsh usage.tcl -i report.txt; echo "exit: $?"
error: both -i and -o are required
usage: convert.tcl -i INPUT -o OUTPUT
  -i  input file
  -o  output file
exit: 2

Reading standard input

A filter reads from standard input when no file is named on the command line. The channel is called stdin and is read with the same commands as a file: gets for one line at a time, read for everything. This makes the script usable in a pipeline.

sum_stdin.tcl
set total 0
set lines 0
set skipped 0

while {[gets stdin line] >= 0} {
    incr lines
    set value [string trim $line]
    if {![string is integer -strict $value]} {
        puts stderr "skipping: $line"
        incr skipped
        continue
    }
    incr total $value
}

puts "lines:   $lines"
puts "skipped: $skipped"
puts "total:   $total"

The loop reads until gets returns -1, which happens at end of input. Blank lines and non-numeric lines are reported on standard error and counted as skipped, but they do not stop the run. The totals are printed to standard output, so stdout can be redirected to a file while the warnings still reach the terminal. The Tcl gets command page describes the return value in more detail, and Tcl exec shows how to run another program and capture its output.

$ printf '10\n20\nabc\n12\n' | tclsh sum_stdin.tcl
skipping: abc
lines:   4
skipped: 1
total:   42

Source

The Tcl 8.6 manual documents the interpreter startup and the commands used to leave a script. The tclsh page describes argv, argc and argv0; the other pages cover status codes and channel input.

This article read argv, argc and argv0, checked positional arguments, parsed flags and options with values, honored the -- terminator, printed usage messages with distinct exit statuses and consumed standard input. The Tcl exit command page covers leaving the interpreter, and Tcl files and directories shows how to open the files that the arguments name.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.