expect 赋值shell变量_如何在Expect条件语句中使用Bash脚本变量

本文介绍了一个Bash脚本,该脚本使用Expect进行sftp操作,并尝试在Expect块中使用Bash变量进行条件判断。同时,讨论了如何从C程序控制脚本执行并将其输出重定向到动态日志文件,以及如何抑制标准输出。解决方案是直接在Expect脚本中处理所有变量和逻辑,避免了Bash和Expect之间的交互问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bd96500e110b49cbb3cd949968f18be7.png

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?

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.

Here is the code:

!/usr/bin/bash

host=$1

user=$2

pass=$3

action=$4

path=$5

echo "Starting...."

function doAction {

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

echo $strAction

/usr/bin/expect < 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

expect "sftp>"

send_user "quit\n"

exit

EOF

}

doAction

echo "DONE....."

For 1. using an Expect script instead worked.

For the logging issue, using log_user 0 and log_file -a helped.

解决方案

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值