11

I want to set a variable b in expect file,here initially i did ssh to a machine through this script,in that machine I want to do fetch a value and set the expect variable using following command:

set b [exec `cat /home/a |grep "work"|awk -F '=' '{print $2}'`]


send_user "$b"

file /home/a have following structure:

home=10.10.10.1

work=10.20.10.1

I am trying to use variable b after printing it but after doing ssh script it is giving:

can't read "2": no such variable

while executing

If I put this output in a file name temp in that machine and try to do:

set b [exec cat ./temp]

then also it gives:

cat: ./temp: No such file or directory

If I do send "cat ./temp" it prints the correct output.

Please let me know where I am going wrong.

Zumo de Vidrio
  • 2,021
  • 2
  • 15
  • 33
Ek1234
  • 407
  • 3
  • 7
  • 17

2 Answers2

8

Single quotes are not quoting mechanism for Tcl, so brace your awk expressions.

% set b [exec cat /home/a | grep "work" | awk -F {=} {{print $2}}]
10.20.10.1

Reference : Frequently Made Mistakes in Tcl

Dinesh
  • 16,014
  • 23
  • 80
  • 122
  • If i use :set b [exec cat /home/a |grep "work"|awk -F {=} {{print $2}}]...it gives extra characters after close-quote while executing and if i put \"work\" cat: invalid option -- 'F' Try 'cat --help' for more information. while executing – Ek1234 Mar 13 '16 at 11:24
5

Assuming you spawned an ssh session, or something similar, send "cat ./temp\r" shows you the file on the remote host, and exec cat ./temp shows you the file on the local host. exec is a plain Tcl command.

Capturing the command output of a send command is a bit of PITA, because you have to parse out the actual command and the next prompt from the output. You need to do something like:

# don't need 3 commands when 1 can do all the work
send {awk -F= '/work/ {print $2}' /home/a}
send "\r"
expect -re "awk\[^\n]+\n(.+)\r\n$PROMPT"   # where "$PROMPT" is a regex that
                                           # matches your shell prompt.

set command_output $expect_out(1,string)
send_user "$command_output\n"
glenn jackman
  • 238,783
  • 38
  • 220
  • 352