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.


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

    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 ]
    echo "there was an error in copying the data" 
mail -s "Success!" someone@example.com


  • 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 4 '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 4 '18 at 19:31
  • I will add this to run on Crontab, to check every hour. – Pedro Lopes Oct 4 '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 4 '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 4 '18 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.