How to use bash script variables in expect conditional statements

隐身守侯 提交于 2019-12-04 07:34:03

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. Good luck.

Accessing Environment Variables from TCL and Expect

Since you are calling this Expect script from another process, you can make use of environment variables. For example, if your parent process has exported action to the environment, then you can access its value within your expect script with:

$::env(action)

In Bash, you can mark the variable for export with the export builtin. For example:

export action

Since I'm not sure how you're invoking the Expect script from C, it's up to you to make sure the variable is properly exported.

Disable Logging to Standard Output

To disable logging to standard output from spawned processes, Expect provides the log_user command. You can prevent your spawned processes from writing to stdout with log_user 0.

The expect(1) manual says:

By default, the send/expect dialogue is logged to stdout (and a logfile if open). The logging to stdout is disabled by the command "log_user 0" and reenabled by "log_user 1". Logging to the logfile is unchanged.

This doesn't actually close standard output, which is generally not what you want anyway. Doing so will cause anything that writes to stdout to throw an error like this:

can not find channel named "stdout"
    while executing
"puts hello"
    (file "/tmp/foo" line 8)

To suppress output to the stdout you can use

command here >/dev/null 2>/dev/null

To write to a log file you can use similar piping (> or >>), or the tee command if you want to write the output in the middle of a long pipe.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!