0

I have some Tcl scripts that are executed by defining variables in the command-line invocation:

$ tclsh84 -cmd <script>.tcl -DEF<var1>=<value1> -DEF<var2>=<value2>

Is there a way to check if var1 and var2 are NOT defined at the command line and then assign them with a set of default values?

I tried the keywords global, variable, and set, but they all give me this error when I say "if {$<var1>==""}": "can't read <var1>: no such variable"

3 Answers 3

5

I'm not familiar with the -def option on tclsh.

However, to check if a variable is set, instead of using 'catch', you can also use 'info exist ':

if { ![info exists blah] } {
  set blah default_value
}
1
  • There's no -def option; tclsh prefers to leave as much as possible to the script. Dec 22, 2015 at 17:36
1

Alternatively you can use something like the cmdline package from tcllib. This allows you to set up defaults for binary flags and name/value arguments, and give them descriptions so that a formatted help message can be displayed. For example, if you have a program that requires an input filename, and optionally an output filename and a binary option to compress the output, you might use something like:

package require cmdline
set sUsage "Here you put a description of what your program does"
set sOptions {
    {inputfile.arg ""  "Input file name - this is required"}
    {outputfile.arg "out.txt"     "Output file name, if not given, out.txt will be used"}
    {compressoutput       "0"      "Binary flag to indicate whether the output file will be compressed"}
}

array set options [::cmdline::getoptions argv $sOptions $sUsage]
if {$options(inputfile) == ""} {puts "[::cmdline::usage $sOptions $sUsage]";exit}

The .arg suffix indicates this is a name/value pair argument, if that is not listed, it will assume it is a binary flag.

0

You can catch your command to prevent error from aborting the script.

if { [ catch { set foo $<var1> } ] } {
    set <var1> defaultValue
}

(Warning: I didn't check the exact syntax with a TCL interpreter, the above script is just to give the idea).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.