bash 如何使用shell命令的输出设置期望变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35968746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to set an expect variable with output of shell command
提问by user2769274
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:
我想在expect文件中设置一个变量b,这里最初我通过这个脚本ssh到一台机器,在那台机器上我想获取一个值并使用以下命令设置expect变量:
set b [exec `cat /home/a |grep "work"|awk -F '=' '{print }'`]
send_user "$b"
file /home/a have following structure:
文件 /home/a 具有以下结构:
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:
我试图在打印后使用变量 b 但在执行 ssh 脚本后它给出:
can't read "2": no such variable
无法读取“2”:没有这样的变量
while executing
If I put this output in a file name temp in that machine and try to do:
如果我将此输出放在该机器的文件名 temp 中并尝试执行以下操作:
set b [exec cat ./temp]
set b [exec cat ./temp]
then also it gives:
然后它也给出:
cat: ./temp: No such file or directory
cat: ./temp: 没有那个文件或目录
If I do send "cat ./temp" it prints the correct output.
如果我发送“cat ./temp”,它会打印正确的输出。
Please let me know where I am going wrong.
请让我知道我哪里出错了。
采纳答案by glenn Hymanman
Assuming you spawned an ssh session, or something similar, send "cat ./temp\r"
shows you the file on the remotehost, and exec cat ./temp
shows you the file on the localhost. exec
is a plain Tcl command.
假设您产生了一个 ssh 会话或类似的东西,send "cat ./temp\r"
向您显示远程主机上的文件,并向exec cat ./temp
您显示本地主机上的文件。exec
是一个普通的 Tcl 命令。
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:
捕获命令的命令输出send
有点 PITA,因为您必须从输出中解析出实际命令和下一个提示。您需要执行以下操作:
# don't need 3 commands when 1 can do all the work
send {awk -F= '/work/ {print }' /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"
回答by Dinesh
Single quotes are not quoting mechanism for Tcl
, so brace your awk
expressions.
单引号不是 的引用机制Tcl
,因此请用括号括住您的awk
表达式。
% set b [exec cat /home/a | grep "work" | awk -F {=} {{print }}]
10.20.10.1
Reference :Frequently Made Mistakes in Tcl
参考:Tcl 中的常见错误