简体   繁体   中英

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). 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.

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.

Tried some from the google references but couldn't really get any closer to a working solution.

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 is an extension of , and Tcl uses square brackets the same way the shell uses backticks: command substitution. 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:

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.

Note that I removed the backticks from the command.

The entire syntax for the Tcl language is described here -- there are only 12 rules. This Q&A involves rules 4, 6, and 7, and tangentially 8 and 9.

You can follow all that @glenn-jackman have suggested. Also keep a check on the single quotes. You may want to replace them with double quotes if you are using bash. check this: http://www.gnu.org/software/bash/manual/html_node/Single-Quotes.html also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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