Shell脚本自动同步FTP文件报错unexpected end of file求助
问题分析与修复
你的脚本触发"unexpected end of file"错误的核心原因是here-doc的结束标记格式错误:在使用<<END_SCRIPT这种here-doc语法时,结束标记END_SCRIPT必须完全顶格书写,不能有任何前导空格或缩进。你的脚本中所有END_SCRIPT前面都带有空格,shell无法识别这是结束标记,会一直读取到脚本末尾都找不到正确的结束标记,因此抛出该错误。
修正后的脚本
#!/bin/bash # Define FTP server details FTP_HOST="host" FTP_USER="ftp_user" FTP_PASS="ftp_pass" REMOTE_FILE="file.text" LOCAL_DIR="/home" LOCAL_FILE="$LOCAL_DIR/$REMOTE_FILE" # Check if local file exists and is up-to-date with the file on the FTP server if [ -f "$LOCAL_FILE" ] then # Get the modification time of the local file LOCAL_MTIME=$(stat -c %Y "$LOCAL_FILE") # Connect to FTP server and get the modification time of the remote file FTP_MTIME=$(ftp -n "$FTP_HOST" <<END_SCRIPT quote USER $FTP_USER quote PASS $FTP_PASS cd script/ ls -l $REMOTE_FILE quit END_SCRIPT | awk '{print $6" "$7" "$8}') # Compare the modification times and download the latest file if necessary if [ "$LOCAL_MTIME" -lt "$(date -d "$FTP_MTIME" +%s 2>/dev/null)" ] then # Remove the old local file rm "$LOCAL_FILE" # Connect to FTP server and download the latest file ftp -n "$FTP_HOST" <<END_SCRIPT quote USER $FTP_USER quote PASS $FTP_PASS cd script/ get $REMOTE_FILE $LOCAL_DIR quit END_SCRIPT echo "File downloaded successfully." else echo "File is up-to-date." fi else # Connect to FTP server and download the file ftp -n "$FTP_HOST" <<END_SCRIPT quote USER $FTP_USER quote PASS $FTP_PASS cd script/ get $REMOTE_FILE $LOCAL_DIR quit END_SCRIPT echo "File downloaded successfully." fi
其他补充修正说明
- 变量引用加双引号:所有变量(如
$LOCAL_FILE、$FTP_HOST)都加上双引号,避免文件名或路径包含空格时出现语法错误。 - date命令增加错误抑制:在
date -d "$FTP_MTIME" +%s后添加2>/dev/null,防止FTP服务器ls -l输出格式不兼容时,date命令报错干扰脚本执行。
额外建议
- FTP的
ls -l输出格式可能因服务器配置不同而变化,部分服务器的日期格式可能包含年份(如旧文件显示年份而非时间),此时date -d可能无法正确解析,建议改用lftp工具,它支持更可靠的文件修改时间获取(如lftp -c "open $FTP_HOST -u $FTP_USER,$FTP_PASS; cd script; echo \$modtime($REMOTE_FILE)")。 - 避免在脚本中明文存储FTP密码,可考虑使用环境变量或
~/.netrc文件存储认证信息。
内容的提问来源于stack exchange,提问作者Cepi Herdiansyah
相关产品推荐
相关产品推荐

