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

Ash*_*ish 5 bash shell sftp copying

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

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

Connected to 10.42.255.209.
sftp> bye
sftp.sh: line 23: put: command not found
Run Code Online (Sandbox Code Playgroud)

请找到以下脚本。

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
Run Code Online (Sandbox Code Playgroud)

nos*_*nos 13

在像这样的简单情况下,您可以使用scpinstad ofsftp并在命令行上指定要复制的文件:

 scp $localpath/* username@10.42.255.209:/$remotepath/
Run Code Online (Sandbox Code Playgroud)

但是,如果您更愿意发出 sftp 命令,那么 sftp 可以从其标准输入读取命令,因此您可以执行以下操作:

  echo "put $localpath/* $remotepath" | sftp username@10.42.255.209
Run Code Online (Sandbox Code Playgroud)

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

sftp username@10.42.255.209 << EOF
put $localpath/fileA $remotepath/
put $localpath/fileB $remotepath/
EOF
Run Code Online (Sandbox Code Playgroud)

最后,您可以将 sftp 命令放在一个单独的文件中,例如sftp_commands.txt,并让 sftp 使用其-b标志执行这些命令:

 sftp -b ./sftp_commands.txt username@10.42.255.209
Run Code Online (Sandbox Code Playgroud)