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.
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.
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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With