Wednesday, April 13, 2022

[SOLVED] Unix command CP to copy a file to multiple directories

Issue

I have folder structure like this:

/home/
   /folder1/
      /backup/
   /folder2/
      /backup/
   /folder3/
   /folder4/
      /backup/
   /folder5/

(As you can see, no all directories "folder" have a directory "backup")

I need to copy the script "checker.php" to all "backup" directories only.

"checker.php" is at:

/home/checker.php

I am using this command:

cp /home/checker.php /home/*/backup/checker.php

But it is not working. Please help.


Solution

The cp command doesn't allow multiple destination directories.

A way forward is to loop through the folders:

for d in /home/*/backup; do 
    cp /home/checker.php "$d"
done


Answered By - oliv
Answer Checked By - David Goodson (WPSolving Volunteer)