SFTP bash shell脚本将文件从源复制到目标

时间:2018-12-13 12:31:17

标签: bash shell sftp copying

我已经创建了一个脚本来将本地文件复制到远程文件夹,该脚本在if条件之外可以正常工作,但是当我将其包含在if条件中时,put命令不起作用并使用sftp协议登录到远程服务器并且在存在时显示错误:找不到put命令

查看执行脚本后发生了什么

Connected to 10.42.255.209.
sftp> bye
sftp.sh: line 23: put: command not found

请找到以下脚本。

echo -e;
echo -e "This script is used to copy the files";
sleep 2;

localpath=/home/localpath/sftp
remotepath=/home/destination/sftp/

        if [ -d $localpath ]
         then
           echo -e "Source Path found"
           echo -e "Reading source path"
           echo -e "Uploading the files"
           sleep 2;

                sftp username@10.42.255.209
                put $localpath/* $remotepath

        else

1 个答案:

答案 0 :(得分:3)

在这种简单情况下,您可以使用scp的{​​{1}} instad并在命令行上指定要复制的文件:

sftp

但是,如果您想发出sftp命令,则sftp可以从其stdin读取命令,因此您可以执行以下操作:

 scp $localpath/* username@10.42.255.209:/$remotepath/

或者您可以使用here document将数据作为stdin传递到sftp,如果您想运行多个sftp命令,则可能会更容易:

  echo "put $localpath/* $remotepath" | sftp username@10.42.255.209

最后,您可以将sftp命令放在单独的文件中,例如sftp username@10.42.255.209 << EOF put $localpath/fileA $remotepath/ put $localpath/fileB $remotepath/ EOF ,并让sftp使用其sftp_commands.txt标志执行这些命令:

-b