How to use Bash script variables in Expect conditional statements

puneet agrawal picture puneet agrawal · Jun 21, 2012 · Viewed 44.9k times · Source

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

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

Answer

Hai Vu picture Hai Vu · Jun 21, 2012

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.