简体   繁体   English

我该如何在Expect脚本中的if条件中使用变量?

[英]How can I use a variable in if condition in expect script?

I am executing expect script on a remote host(say A) and I want to fetch some environment variables from that remote host(A). 我正在远程主机(例如A)上执行Expect脚本,我想从该远程主机(A)中获取一些环境变量。 Depending on the remote host's(A) environment variables, I would like to perform some conditional operations on that host(A) and on the host(B) from which the expect script is being run. 根据远程主机(A)的环境变量,我想在运行期望脚本的主机(A)和主机(B)上执行一些条件操作。

I could fetch the remote variables and set values in the remote variables. 我可以获取远程变量并在远程变量中设置值。 I couldn't execute the if condition as may be I am having issues figuring out the right syntax/format. 我无法执行if条件,可能是我在找出正确的语法/格式时遇到了问题。

Tried some from the google references but couldn't really get any closer to a working solution. 从google参考资料中尝试了一些方法,但实际上无法找到更有效的解决方案。

send "export vers=`rpm -q --queryformat '%{RELEASE}' rpm | grep -o '.$'`\r"
send "echo \$vers\r"
expect -re $prompt
send "`if [[ \$vers -lt 7 ]]; then echo 'RHEL Version is \$vers'; else echo 'RHEL Version is \$vers'; fi`\r"

Getting below error: 出现以下错误:

invalid command name "$vers"
    while executing
"\$vers -lt 7 "
    invoked from within
"[ \$vers -lt 7 ]"
    invoked from within
"send "`if [[ \$vers -lt 7 ]]; then echo 'RHEL Version is \$vers'; else echo 'RHEL Version is \$vers'; fi`\r""

Need the expect script to execute "if" condition correctly and pass the value to the remote host and my local. 需要Expect脚本正确执行“ if”条件并将该值传递给远程主机和我的本地主机。

expect is an extension of , and Tcl uses square brackets the same way the shell uses backticks: command substitution. Expect是的扩展,Tcl使用方括号,就像shell使用反引号一样:命令替换。 You need to escape the brackets in your double quoted string: 您需要转义双引号字符串中的方括号:

send "if \[\[ \$vers -lt 7 \]\]; then echo 'RHEL Version is \$vers'; else echo 'RHEL Version is \$vers'; fi\r"

Or, avoid the backslashes by using Tcl's non-interpolating quoting mechanism: 或者,通过使用Tcl的非插值引用机制来避免反斜杠:

send {if [[ $vers -lt 7 ]]; then echo 'RHEL Version is $vers'; else echo 'RHEL Version is $vers'; fi}
send "\r"

Curly braces in Tcl are like the shells's single quotes. Tcl中的花括号类似于炮弹的单引号。

Note that I removed the backticks from the command. 请注意,我从命令中删除了反引号。

The entire syntax for the Tcl language is described here -- there are only 12 rules. Tcl语言的整个语法在此处描述-只有12条规则。 This Q&A involves rules 4, 6, and 7, and tangentially 8 and 9. 该问答涉及规则4、6和7,以及切线8和9。

You can follow all that @glenn-jackman have suggested. 您可以按照@ glenn-jackman的建议进行操作。 Also keep a check on the single quotes. 还要检查单引号。 You may want to replace them with double quotes if you are using bash. 如果您使用的是bash,则可能需要用双引号替换它们。 check this: http://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html also. 请检查以下内容: http//www.gnu.org/software/bash/manual/html_node/Single-Quotes.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM