gpt4 book ai didi

error-handling - 捕获Expect脚本的退出代码

转载 作者:行者123 更新时间:2023-12-03 08:51:35 24 4
gpt4 key购买 nike

我有一个期望脚本,它将文件从一台服务器传输到另一台服务器。该期望脚本已由Shell脚本启动。如果源代码中提供了期望脚本,则该脚本可以传输该文件,并且给出零退出代码。但是,当文件在源代码中不可用时,脚本将不会传输文件,但仍会给出零退出代码。

如何捕获期望脚本的正确退出代码。

test.sh:

#!/bin/sh

DT=`date +%Y%m%d`
RXHOME=/tmp'

x_server=A1234
x_file="test_${DT}.dat"

cd $RXHOME/scripts

./test.exp ${x_server} ${x_file}
if [ $? -ne 0 ]
then
echo "ERROR : Expect script encountered an error."
exit 1
fi

test.exp:
#!/usr/local/bin/expect -f

set timeout -1
set XSERVER [lindex $argv 0]
set XFILE [lindex $argv 1]

set uid "user"
set pwd "password"
set srcDir "/tmp/src"
set trgDir "/tmp/trg"

spawn /usr/ldir/bin/sftp ${uid}@${XSERVER}

expect -re "Are you sure you want to continue connecting (yes/no)?" {
send -- "yes\r"
expect -re "assword: "
send -- "$pwd\r"
} -re "assword: " {
send -- "$pwd\r"
}
expect -re "sftp> "
send -- "put ${srcDir}/${XFILE} ${trgDir}/test_file.txt\r"
expect "sftp> "
send -- "bye\r"
expect eof

catch wait result
exit [lindex $result 3]

当源中没有可用文件时的示例输出:
+ + date +%Y%m%d
DT=20160919
+ RXHOME=/tmp
+ x_server=A1234
+ x_file=test_20160919.dat
+ cd /tmp/scripts
+ ./test.exp A1234 test_20160919.dat
spawn /usr/ldir/bin/sftp user@A1234
Connecting to A1234...

user@A1234's password:
sftp> put /tmp/src/test_20160919.dat /tmp/trg/test_file.txt
File "/tmp/src/test_20160919.dat" not found.
sftp> bye
+ [ 0 -ne 0 ]
$

如您所见,即使没有文件传输到目标(因为源中不存在该文件),脚本仍以零退出代码退出。

最佳答案

您必须自己处理错误。尝试这样:

set err 0
send -- "put ${srcDir}/${XFILE} ${trgDir}/test_file.txt\r"
expect {
-re "File .* not found" {
set err 1
exp_continue
}
"sftp> "
}
send -- "bye\r"
expect eof

exit $err

关于error-handling - 捕获Expect脚本的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39588813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com