foreach循环中的空值-TCL-Unix脚本

时间:2019-03-26 14:56:08

标签: shell unix foreach tcl

在以下脚本中,即使列表中包含值,我在以下脚本中也获得了变量$ tclItem的空值。

请您检查一下我想念的东西吗?

FTP_USER="xxxxx"
FTP_SERVER="xxxxx"
FTP_PWD="xxxx"
FTP_DROP_DIR="DROP/Archive"
LOGFILE="\tmp\log.txt"

FILES_TO_ARCHIVE="$(cat $LOGFILE | grep '.txt' | awk ' !/Fetching/' | tr -d '\r') "
echo "Files to Archive..."
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
echo $FILES_TO_ARCHIVE
echo ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"


expect <<END 
 spawn sftp $FTP_USER@$FTP_SERVER
 expect "*password: " 
 send "$FTP_PWD\r";
 expect "sftp> "

foreach tclItem {$FILES_TO_ARCHIVE } {
 #puts $tclItem
 send "ls $FTP_DROP_DIR/$tclItem\r"
 expect "sftp> "
};
 send "quit\r"
END

这是我收到的输出。

Files to Archive.....
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
test1.txt test2.txt test3.txt test4.txt
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

spawn sftp abcdef@sftp.server.com
abcdef@sftp's password:
sftp> ls DROP/Archive/
sftp> ls DROP/Archive/
sftp> ls DROP/Archive/
sftp> ls DROP/Archive/
sftp> invalid command name "test2.txt"
    while executing
"test2.txt"

1 个答案:

答案 0 :(得分:1)

与其使用字符串替换将数据注入代码(一种充满安全问题的做法),而是通过环境将变量从bash传递到expect

# Environment variables should be lowercase except for special/reserved names meaningful
# to the operating system; http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html

ftp_user="xxxxx"
ftp_server="xxxxx"
ftp_pwd="xxxx"
ftp_drop_dir="DROP/Archive"
logfile="/tmp/log.txt"
files_to_archive="$(awk '/[.]txt/ && !/Fetching/' <"$logfile" | tr -d '\r')"

export ftp_user ftp_server ftp_pwd ftp_drop_dir files_to_archive

expect <<'END'
 spawn sftp $env(ftp_user)@$env(ftp_server)
 expect "*password: " 
 send "$env(ftp_pwd)\r";
 expect "sftp> "

 set fileList [split $env(files_to_archive) "\n"]

 foreach tclItem $fileList {
   send "ls $env(ftp_drop_dir)/$tclItem\r"
   expect "sftp> "
 };
 send "quit\r"
END

注意:

  • 使用export将使Shell变量在子流程中可用作环境变量。可以预期,$env(foo)允许读取环境变量foo
  • 使用<<'EOF'代替<<EOF会使bash将代码原样准确地传递给expect ,而无需进行任何更改。 (因此,$tclItem仍为$tclItem,而不是在expect甚至开始之前都没有用空字符串代替)。