SFTP bash shell script to copy the file from source to destination
Asked Answered
P

3

8

I have created one script to copy the local files to the remote folder. The script is working fine outside of if condition. But when I enclosed inside the if condition the put command is not working. It logged into the remote server using SFTP protocol and when exist it's showing the error:

put command not found

See what is happening after executing the script:

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

Please find the below script.

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 [email protected]
        put $localpath/* $remotepath

else
Parcheesi answered 13/12, 2018 at 12:31 Comment(2)
You could simplify this and use scp...: scp localpath [email protected]:/remote/path/Stickybeak
Maybe sftp [email protected] <<< "put $localpath/* $remotepath"?Indulgent
I
26

In a simple case such as this, you could use scp instad of sftp and specify the files to copy on the command line:

 scp $localpath/* [email protected]:/$remotepath/

But if you would rather want to issue sftp commands, then sftp can read commands from its stdin, so you can do:

  echo "put $localpath/* $remotepath" | sftp [email protected]

Or you can use a here document to pass data as stdin to sftp, which might be easier if you want to run several sftp commands:

sftp [email protected] << EOF
put $localpath/fileA $remotepath/
put $localpath/fileB $remotepath/
EOF

Finally, you could place the sftp commands in a separate file, say sftp_commands.txt , and have sftp execute those commands using its -b flag:

 sftp -b ./sftp_commands.txt [email protected]
Intend answered 13/12, 2018 at 12:38 Comment(1)
Just a minor info to add clarity. The 'here' script/document can be saved to a shell file and run using bash.Uphill
R
0

I got the result using this format

HOST='xyz.abc.com'
USER='xyzasd'
REMOTEPATH='/var/www/data-csv/'
file_name='/tmp/sample.csv'


sftp $USER@$HOST <<EOF
cd  /var/www/data-csv/
put $file_name
EOF

It will ask for password if the user have a password. Otherwise this code works fine.

Renitarenitent answered 31/3, 2022 at 11:17 Comment(3)
That's what the answer by @nos says already.Brooklet
sry when I was looking it wasnt there.Renitarenitent
It's there since 2018.Brooklet
T
-1

This code worked for me for reference read https://help.oclc.org/Librarian_Toolbox/Exchange_files_with_OCLC/Upload_files_with_SFTP/40SFTP_commands?sl=en

uploadFileToMFT(){
sftp -P ${PORT_NO} ${HOST_NAME}@${HOST_ID} <<EOF
cd /mdm_dev05
put ${EXPORT_OUTPUT}'/'${ID}'/'${F_NAME}
quit
EOF

}
Tyr answered 8/10, 2021 at 7:7 Comment(1)
That's what the answer by @nos says already.Brooklet

© 2022 - 2025 — McMap. All rights reserved.