bash – 在脚本化命令行SFTP会话中检测上载成功/失败?

我正在编写一个BASH shell脚本,将目录中的所有文件上传到远程服务器,然后删除它们.它将通过CRON作业每隔几个小时运行一次.

我的完整脚本如下.基本问题是,应该判断文件是否成功上传的部分不起作用.无论上载是否成功,SFTP命令的退出状态始终为“0”.

如何判断文件是否正确上传,以便我知道是删除文件还是让它删除

#!/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命令进行上载.

如果批量处理SFTP会话,退出状态为$?会告诉你它是否是转移失败.
echo "put testfile1.txt" > batchfile.txt
sftp -b batchfile.txt user@host
if [[ $? != 0 ]]; then
  echo "Transfer Failed!"
  exit 1
else
  echo "Transfer complete."
fi

编辑添加:这是我们在工作中的生产脚本中使用的东西,所以我确信它是有效的.我们不能使用scp,因为我们的一些客户在SCO Unix上.

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...