我的bash脚本中有一个数组:
my_file=("a.txt" "b.txt" "c.txt" "d.txt" "e.txt")
现在在同一文件中,我想使用Expect并进行循环以获取sftp中的某些文件。这是我的代码
/usr/bin/expect <<EOF
set timeout -1
array set param ${!my_file[@]}
spawn sftp $sftp_option $user@$host
expect "Password:"
send "$pswd\r"
expect "sftp>"
for arg in $param; do
send "mget $arg*\r"
expect "sftp>"
done
send "bye\r"
EOF
使用该代码,我无法使用上面的数组进行循环。我得到这样的错误:
错误#args:应为“数组集arrayName列表”在执行时“数组集参数0 1”
完整代码:
#!/bin/bash
export PATH=$PATH:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/root/bin;
homeDir=/home/jlo_apps/daemon/jlo_ex/collection/wssh;
filePID=$homeDir/rsync_rfs_bbni.pid;
trap "rm $filePID; exit" SIGHUP SIGINT SIGTERM;
if [ -e $filePID ]; then
datenow=`date`;
echo "[ Rsync ] There are rsync processes still running...";
echo "========================= $datenow =========================";
exit 1;
else
echo $$ > $filePID;
fi
. $homeDir/get_rfs_bni.conf;
strconn="$dbuser/$dbpass@$dbhost:$dbport/$dbsid";
profile=`$sqlldr_path -s $strconn <<< "select host|| '|' ||username|| '|' ||password|| '|' ||port|| '|' ||outdir from p_epdp where bank='BBNI';" | tail -2 | head -1`;
mapfile mid < <($sqlldr_path -s $strconn <<< "select distinct(substr(mid, 0, 13)) from p_mid where kode_bank = 'BBNI';" | tail -3 | head -2);
host=$(echo $profile | cut -d"|" -f1);
user=$(echo $profile | cut -d"|" -f2);
pswd=$(echo $profile | cut -d"|" -f3);
port=$(echo $profile | cut -d"|" -f4);
outdir=$(echo $profile | cut -d"|" -f5);
/usr/bin/expect <<EOF
set timeout -1
spawn sftp $sftp_option $user@$host
expect "Password:"
send "$pswd\r"
expect "sftp>"
send "cd $outdir\r"
expect "sftp>"
send "lcd $rfshome\r"
expect "sftp>"
foreach arg {${mid[@]}} {
send "mget $arg*\r"
expect "sftp>"
}
send "bye\r"
EOF
rm $filePID;
sleep 10;
datenow=`date`;
echo "========================= $datenow =========================";
在bash和Expect之间没有单独文件的情况下,是否可以解决此问题?
为什么要在bash脚本的期望块中打扰命令行处理。
相反,您可以执行以下操作:
#!/bin/bash
my_file=("a.txt" "b.txt" "c.txt" "d.txt" "e.txt")
for file in "${my_file[@]}"; do
/usr/bin/expect <<EOF
set timeout -1
spawn sftp $sftp_option $user@$host
expect "Password:"
send "$pswd\r"
expect "sftp>"
send "mget $file*\r"
expect "sftp>"
send "bye\r"
EOT
done
用于插入数组值的正确语法是
array set param ${my_file[@]}
没有!
,但这会产生
array set param a.txt b.txt c.txt d.txt e.txt
但是,用于创建数组的Expect语法看起来像
array set param {one one.txt two two.txt}
具有交替的键和值(更像是关联数组,而不仅仅是值列表)。但是,您仍然不能在Expect脚本中使用shell for
循环;该语言使用完全不同的语法(期望基于TCL,而不是Shell脚本)。
可能您正在寻找类似的东西
/usr/bin/expect <<EOF
set timeout -1
spawn sftp $sftp_option $user@$host
expect "Password:"
send "$pswd\r"
expect "sftp>"
foreach arg {${my_file[@]}} {
send "mget $arg*\r"
expect "sftp>"
}
send "bye\r"
EOF
我在Pass bash array to expect script中写下了适当的TCL循环语法