0

I would like to make a script that detects a new file in different folders like:

  • /home/pedro/XX/file1_082018.zip
  • /home/pedro/XX/file2_082018.zip

where XX indicates a non-fixed position country name (E.G. Brasil, Argentina, Chile, ...)

Once the new file has been detected, I would like to copy this file somewhere else:

cp /home/pedro/BR/file1_082018.zip /home2/pedro/BR/file1_082018.zip

And if the copy to the new folder is complete, send a mail to inform. New file /file1_082018.zip is available.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

1 Answers1

0

According to cp man, you can check the return code of cp.

EXIT STATUS
    The cp utility exits 0 on success, and >0 if an error occurs.

The exit code of the last operation is actually saved in the special variable $?, for example:

cp -v /home/pedro/BR/file1_082018.zip /home2/pedro/BR/file1_082018.zip
echo $? >> exit_status.log

Then check the value of $?

for i in $(cat countries.txt); do      #countries.txt is a file contain directories names

cp -v /home/pedro/${i}/file1_082018.zip /home2/pedro/${i}/file1_082018.zip
echo $? >> exit_status.log

if [ $? -ne 0 ]
  then
    echo "there was an error in copying the data" 
 exit
  else
mail -s "Success!" someone@example.com
  fi

done

  • Thank you so much for the fast reply. The problem is.. i have to check every folder for every country.. like /home/pedro/BR/ /home/pedro/AR/ /home/pedro/CL/ and copy to the correct folder /home2/pedro/BR/ /home2/pedro/AR/ /home2/pedro/CL/ – Pedro Lopes Oct 04 '18 at 19:16
  • Hi @goro thanks again. i will try to be more clear. I have this tree directories /home/pedro/XX .. where XX indicates a country.. So, if we receive any new file inside this folders, i have to copy to another folder, After the copy i have to send a mail with the names of the files coppied and the country. – Pedro Lopes Oct 04 '18 at 19:31
  • I will add this to run on Crontab, to check every hour. – Pedro Lopes Oct 04 '18 at 19:38
  • Eg. If in folder /home/pedro/AR/ have 4 files, and i receive 2 new, i just want to copy this 2 new or I can copy the 4 files and remove after conclude. – Pedro Lopes Oct 04 '18 at 19:40
  • You are a genius... so i use the command rsync -u to update the folder.. and how can i detect witch files was coppied and send a mail ? – Pedro Lopes Oct 04 '18 at 20:02
  • Doesnt work.. cat mylog.log 2018/10/04 16:11:23 [1766] building file list 2018/10/04 16:11:23 [1766] .d.....g... ./ 2018/10/04 16:11:23 [1766] .d..t...... AR/ 2018/10/04 16:11:23 [1766] sent 266 bytes received 27 bytes 586.00 bytes/sec 2018/10/04 16:11:23 [1766] total size is 1.73M speedup is 5907.56 – Pedro Lopes Oct 04 '18 at 20:13
  • @Pedro Lopes. Would you please either edit the question or post new question? –  Oct 04 '18 at 20:14