0

Currently I follow the following steps for copying a file from server_x to server_y (Let's suppose I run this code on 20th April 2021 = 202104)

sshpass -p "my_server_y_password" ssh myusernameY@server_y
sshpass -p "my_server_x_password" scp myusernameX@server_x:server_x/file/path/file_202104.txt server_y/file/path

I want to get this code to run on 20th of every month and also use the YYYYMM date format for searching the file. If the file does not exist, it shouldn't do anything

I think that the code should look like (inside my_bash_script.sh)

year_month="$(date +'%Y%m')"
FILE=file/path/file_$(year_month).txt
# somehow check if file from server_x exists (currently I don't know how to do it on a different server)
if test -f "$FILE"; then 
    sshpass -p my_server_y_password ssh myusernameY@server_y
    sshpass -p "my_server_x_password" scp myusernameX@server_x:${FILE} server_y/file/path
fi

And, after this, I should run my script

 * * 20 * * my_bash_script.sh

I am sure there are much more elegant solutions to approach my problem. Also, I think some parts of my code don't even work properly. Please help me finding a proper solution for my task

Edit reasons: I replaced my former code with crontab command as suggested by @looppool

pentavol
  • 119
  • 1
  • 10

2 Answers2

1

Yes, there are much more elegant solutions to this. Use cron. See this answer as an example. Simply change the third parameter for your convenience:

 * * 20 * * my_bash_script.sh

For your updated question, you don't have to check for yourself whether or not a file is there or if it is updated. Simply use the rsync-command to copy a file from one server to another. It will only update the files which have changed. rsync also understands the ssh-Protocol, you'll easily a lot of examples on the internet on how to do that.

looppool
  • 9
  • 2
  • Great! So I can use this instead of nohup and "TodayDate=$(date +%d) if [ "$TodayDate" -eq "20" ]" part. However, how can I check the existence of a file in a remote server? – pentavol Apr 10 '21 at 12:36
  • I also edited my question. Now it contains your cron script, which seems more elegant – pentavol Apr 10 '21 at 12:39
  • I've just saw you also edited your answer. Please modify your answer to write every step (how my my_bash_script.sh should look like, where / how should I write "* * 20 * * my_bash_script.sh" etc) and I will accept your answer. Thanks a lot! – pentavol Apr 10 '21 at 17:47
0

However, how can I check the existence of a file in a remote server?

No, as aforementioned, you don't need to do it by yourself, unless if you want to do extra operations on existing files.

If you just want to sync files, then just simply try:

rsync path/to/local_file remote_host:path/to/remote_directory

Let me know if it can work for you.

Bruce Wen
  • 61
  • 1
  • 4