Question

I need to use the value of a variable inside another variable.

This is what I tried..

set cmd_ts "foo bar"
set confCmds {
    command1
    command2
    $cmd_ts
}
puts "confCmds = $confCmds"

But instead of getting

confCmds = 
    command1
    command2
    foo bar

I am getting:

confCmds =
    command1
    command2
    $cmd_ts

P.S. I tried the following to no avail

  1. $cmd_ts
  2. "$cmd_ts"
  3. {$cmd_ts}
  4. \$cmd_ts
Was it helpful?

Solution

(almost) nothing will work as long as you use curly braces. The best suggestion is to use the list command:

set confCmds [list command1 command2 $cmd_ts]

I say (almost) because you can use subst to do variable substitution on confCmds, but that's not really what you want and that is fraught with peril. What you want is a list of words, one or more of which may be defined by a variable. That is precisely what the above solution gives you.

If you want, you can spread the commands on more than one line by using the backslash:

set confCmds [list \
    command1 \
    command2 \
    $cmd_ts \
]

This solution assumes that what you want is a tcl list. This may or may not be what you want, it all depends on how you treat this data downstream.

In a comment you wrote that what you really want is a string of newline-separated items, in which case you can just use double quotes, for example:

set confCmds "
    command1
    command2
    $cmd_ts
"

That will give you a string with multiple lines separated by newlines. Be careful of trying to treat this as a list of commands (ie: don't do 'foreach foo $confCmds') because it can fail depending on what is in $cmd_ts.

OTHER TIPS

Bryan's answer is good, apart from a typo I can't fix with my rep. (the list in the first command should be ended with a square bracket).

If you want to do anything useful with the commands, you probably want them as a list, but if you just want them separated by a new line do this at the end:

set confCmds [join $confCmds "\n"]

If you must have the list defined as you have it, you can also use the subst command, which will perform the substitution that the curly braces are preventing:

subst $confCmds
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top