如何在Expect条件语句中使用Bash脚本变量 [英] How to use Bash script variables in Expect conditional statements

查看:415
本文介绍了如何在Expect条件语句中使用Bash脚本变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Bash脚本,并使用Expect做sftp.现在在Expect块中,我想在条件语句中访问Bash变量.但是,我无法这样做.该怎么办?

I am writing a Bash script and using Expect to do sftp. Now in the Expect block I want to access a Bash variable in a conditional statement. But, I am unable to do so. How can do this?

此外,此脚本的执行由C程序控制,我想将输出重定向到日志文件(该文件也是动态的).我可以这样做,并禁止标准输出中的所有输出吗?

Also, the execution of this script is controlled from a C program and I want redirect the output to a log file (which again is dynamic). Can I do that and suppress all the output on standard output.

这是代码:

!/usr/bin/bash
host=$1
user=$2
pass=$3
action=$4
path=$5
echo "Starting...."

function doAction {

strAction="\""$action"\""
echo $strAction

/usr/bin/expect <<EOF > logfile.txt
**set bashaction $strAction**
spawn sftp $user@$host

expect "password:"
send "$pass\r"
expect"sftp>"
send "cd $path\r"
**if {$bashaction == "TEST"} {**
  expect "sftp>"
  send "prompt\r"
}

expect "sftp>"
send <sftp command>
expect "sftp>"
send_user "quit\n"

exit
  EOF
}

doAction
echo "DONE....."

对于1.使用Expect脚本代替. 对于日志记录问题,使用log_user 0log_file -a <file>很有帮助.

For 1. using an Expect script instead worked. For the logging issue, using log_user 0 and log_file -a <file> helped.

推荐答案

您不需要使用Bash. Expect可以处理所有这些事情:

You don't need to use Bash. Expect can handle all that:

#!/usr/bin/expect

set host [lindex $argv 0]
set user [lindex $argv 1]
set pass [lindex $argv 2]
set action [lindex $argv 3]
set path [lindex $argv 4]
puts "Starting...."

puts "\"$action\""
spawn sftp $user@$host

expect "password:"
send "$pass\r"

expect"sftp>"
send "cd $path\r"

if {$action == "TEST"} {
    # Do something
} else {
    # Do something else
}

expect "sftp>"
send_user "quit\r"

puts "DONE....."

来自Bash的Tcl/Expect语法有点奇怪,但是扩展上面的框架应该没有任何问题.

Coming from Bash, the Tcl/Expect syntax is a little strange, but you should not have any problem expanding the above skeleton.

这篇关于如何在Expect条件语句中使用Bash脚本变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆