I've this part of TCL/expect code:
commands.txt sample content:
configure terminal
interface Vlan10
ip address 192.168.1.1 255.255.255.0
set commands "commands.txt"
#
set f [open "$commands"]
set commands [split [read $f] "\n"]
close $f
#
foreach cmd $commands {
expect {
"*#" {
send "$cmd\n"
}
and it works as intended, for every command to be sent to a switch, it does "expect Cisco prompt *# then send commands in list line by line, with newline at the end".
Now I would like to use a variable previously set in the script (like: set ip "192.168.2.2") inside the command file, like this:
cat commands.txt
configure terminal
Interface Vlan10
ip address $ip 255.255.255.0
how can I do that?
Now, the variable gets ignored and obviously gets sent as literal string. eg:
ip address $ip 255.255.255.0
thanks
Use the subst
command: https://www.tcl.tk/man/tcl8.6/TclCmd/subst.htm
It performs all the usual string interpolations like $
for variable substitutions and []
for command substitutions and \
for backslash substitutions.
You can limit it to variable substitution only by using the right argument:
send "[subst -nocommand -nobackslashes $cmd]\n"