Version 1 of command options

Updated 2001-09-10 15:22:27

"command options" suggests several distinct topics:

  • tclsh and wish arguments
  • command-line options as seen (through $::argv) of Tcl-coded applications
  • idioms for parsing variable (args) arguments seen by pure-Tcl procs.

Certain considerations are common to all these, and are convenient to treat here in a unified way.



[Many people write their own "... -arg1 val1 -arg2 val2 ..." processing, because it's so easy to use Tcl associative arrays (see "Arrays / Hash Maps") simply as the "optional arguments" section in Tcl Gems does ...]


Here is the start of some code to show at least one method of doing command line parsing. Hopefully people will contribute other samples as appropriate.

 # If this script was executed, and not just "source"'d, handle argv
 if { [string compare [info script] $argv0] == 0} {
      while {[llength $argv] > 0 } { 
         set flag [lindex $argv 0]
         switch -- $flag {
          "-bool" {
                  set bool 1
                  set argv [lrange $argv 1 end]
                  }
          "-option" {
                  set value [lindex $argv 1]
                  set argv [lrange $argv 2 end]
                   }
           default { break }
      }
    }
 }

 foreach file $argv {
    puts "[format "file: %s" $file]"
 }

A related topic: "Syntax parsing in Tcl".


Tcl syntax help - Arts and crafts of Tcl-Tk programming