Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transfer files using lftp in a Bash script

I have server A test-lx, and server B test2-lx, I want to transfer files from server A to server B.

While transferring the files, I'll need to create a directory only if it does not exist. How can I check if a directory exist during the lftp conenction? How can I out several files in one command instead of doing this in two lines?

Is there an option to use find -maxdepth 1 -name DirName?

Here is my code:

lftp -u drop-up,1Q2w3e4R   ftp://ta1bbn01:21 << EOF

cd $desFolder
mkdir test
cd test
put $srcFil
put $srcFile

bye
EOF
like image 757
Alex Brodov Avatar asked May 08 '26 13:05

Alex Brodov


2 Answers

A simple way with ftp:

#!/bin/bash

ftp -inv ip << EOF
user username password

cd /home/xxx/xxx/what/you/want/
put what_you_want_to_upload

bye
EOF

With lftp:

#!/bin/bash

lftp -u username,password ip << EOF

cd /home/xxx/xxx/what/you/want/
put what_you_want_to_upload

bye
EOF

From the lftp manual:

-u <user>[,<pass>]  use the user/password for authentication

You can use mkdir for creating a directory. And you can use the put command several times, like this:

put what_you_want_to_upload
put what_you_want_to_upload2
put what_you_want_to_upload3

And you can close the connection with bye.


You can check if a folder exists or not like this:

#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; ls /home/test1/test1231")

if [ "$checkfolder" == "" ];
then
echo "folder does not exist"
else
echo "folder exist"
fi

From the lftp manual:

-c <cmd>            Execute the commands and exit

And you can open another connection for 'put'ting some files.


I don't know how to check a folder exists or not with one connection, but I can do that like this. Maybe you can find a better solution:

#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; ls /home/test1/test2")

if [ "$checkfolder" == "" ];
then

lftp -u user,pass ip << EOF

mkdir test2
cd test2
put testfile.txt
bye
EOF

else

echo "The directory already exists - exiting"

fi
like image 54
onur Avatar answered May 10 '26 06:05

onur


I used the same basic coding outline as phe. However, I found that using ls /foldername will output "folder does not exist" if the folder is empty. To solve this, I use

#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; ls | grep /test1231")

if [ "$checkfolder" == "" ];
then
echo "folder does not exist"
else
echo "folder exists"
fi

Please note this only works if the folder is in the root directory. For subdirectories in a folder, the following should work.

#!/bin/bash
checkfolder=$(lftp -c "open -u user,pass ip; find | grep home/test1/test1231")

if [ "$checkfolder" == "" ];
then
echo "folder does not exist"
else
echo "folder exists"
fi
like image 38
edf242 Avatar answered May 10 '26 04:05

edf242



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!