我正在编写一个BASH
shell脚本,将目录中的所有文件上传到远程服务器,然后删除它们.它将通过CRON作业每隔几个小时运行一次.
原文链接:https://www.f2er.com/bash/385562.html我的完整脚本如下.基本问题是,应该判断文件是否成功上传的部分不起作用.无论上载是否成功,SFTP命令的退出状态始终为“0”.
如何判断文件是否正确上传,以便我知道是删除文件还是让它删除?
@H_403_5@#!/bin/bash # First,save the folder path containing the files. FILES=/home/bob/theses/* # Initialize a blank variable to hold messages. MESSAGES="" ERRORS="" # These are for notifications of file totals. COUNT=0 ERRORCOUNT=0 # Loop through the files. for f in $FILES do # Get the base filename BASE=`basename $f` # Build the SFTP command. Note space in folder name. CMD='cd "Destination Folder"\n' CMD="${CMD}put ${f}\nquit\n" # Execute it. echo -e $CMD | sftp -oIdentityFile /home/bob/.ssh/id_rsa bob@ftp.example.edu # On success,make a note,then delete the local copy of the file. if [ $? == "0" ]; then MESSAGES="${MESSAGES}\tNew file: ${BASE}\n" (( COUNT=$COUNT+1 )) # Next line commented out for ease of testing #rm $f fi # On failure,add an error message. if [ $? != "0" ]; then ERRORS="${ERRORS}\tFailed to upload file ${BASE}\n" (( ERRORCOUNT=$ERRORCOUNT+1 )) fi done SUBJECT="New Theses" BODY="There were ${COUNT} files and ${ERRORCOUNT} errors in the latest batch.\n\n" if [ "$MESSAGES" != "" ]; then BODY="${BODY}New files:\n\n${MESSAGES}\n\n" fi if [ "$ERRORS" != "" ]; then BODY="${BODY}Problem files:\n\n${ERRORS}" fi # Send a notification. echo -e $BODY | mail -s $SUBJECT bob@example.edu由于一些让我头疼的操作方面的考虑因素,我无法使用SCP.远程服务器在Windows上使用WinSSHD,并且没有EXEC权限,因此任何SCP命令都会失败并显示消息“通道0上的执行请求失败”.因此,必须通过交互式SFTP命令进行上载.