Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set an expect variable with output of shell command

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.

like image 509
Ek1234 Avatar asked Mar 13 '16 09:03

Ek1234


People also ask

How do you store expect output in a variable?

The expect command is used to recover text from the input buffer. Each time a match is found, the buffer up to the end of that match is cleared, and saved to $expect_out(buffer). The actual match is saved to $expect_out(0,string). The buffer then resets.

What is expect command in Linux?

Linux expect Command SyntaxEnables interacting with the program. Expect uses TCL (Tool Command Language) to control the program flow and essential interactions. Some systems do not include Expect by default. To install it with apt on Debian-based systems, run the following in the terminal: sudo apt install expect.


2 Answers

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

like image 146
Dinesh Avatar answered Oct 16 '22 18:10

Dinesh


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"
like image 24
glenn jackman Avatar answered Oct 16 '22 19:10

glenn jackman