how to set an expect variable with output of shell command
Solution 1
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"
Solution 2
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
Ek1234
Updated on July 19, 2022Comments
-
Ek1234 almost 2 years
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.
-
Ek1234 about 8 yearsIf 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