Version 0 of env changing arguments

Updated 2014-10-07 10:13:31 by suchenwi

Richard Suchenwirth 2014-10-07 - The global env array can be used to pass parameters into a script. In Unixoid shells, you can set a temporary env variable in front of a command:

/etc/us/trecs/fss $ FOO=2 echo hello
hello
/etc/us/trecs/fss $ echo $FOO

From inside a Tcl script, you can check if a particular environment variable exists, and use it:

if [info exists ::env(FOO)] {set foo $::env(FOO)} else {set foo ""}

As a variation, programs like awk also accept such variables in the argument list:

$ awk '{print $1}' FS=, input.txt

The following function finds, applies and removes such specifications from an argument list:

proc getenv _argv {
    upvar 1 $_argv argv
    global env
    foreach arg $argv {
        if [regexp {([A-Za-z0-9_]+)=(.+)} $arg -> var val] {
            set env($var) $val
            set pos [lsearch -exact $argv $arg]
            set argv [lreplace $argv $pos $pos]
        }
    }
}

Testing in an interactive tclsh:

% set argv {foo FS=, bar}
foo FS=, bar
% getenv argv

% set argv
foo bar
% set env(FS)
,