-1

Given source file path and destination path. How to write a shell script to copy source file in all folders of destination directory?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Buddha
  • 51
  • 1
  • 5
  • 3
    Can you add some details / examples, to clarify what you want? (I ask because codeforester clearly interprets your question differently than me.) – ruakh May 29 '17 at 04:41
  • @ruakh: what was wrong with my edit? I followed the guidelines here: https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ – codeforester May 29 '17 at 04:42
  • 3
    @codeforester: You changed the title to ask the question you wanted it to ask, not the question that seems to be in the OP's mind. You are thinking of making one copy of the file. The OP appears to want one copy of the file in each sub-directory of the target directory, so if there are 20 sub-directories, there will be 20 copies of the file — one per sub-directory. Now, that may just be a problem with use of English, but the surface question seems to be that — and your answer doesn't address it. Now, I may be wrong. Ruakh may have had yet another meaning in mind. The OP needs to clarify! – Jonathan Leffler May 29 '17 at 04:47
  • Sorry gentlemen. You are right. I will hope OP will clarify the point. – codeforester May 29 '17 at 04:49
  • @tripleee: If my [interpretation](https://stackoverflow.com/questions/44234630/shell-copy-a-file-in-all-folders-of-a-directory#comment75479217_44234630) of the question is right, the duplicate question is not the correct duplicate. – Jonathan Leffler May 29 '17 at 05:25

2 Answers2

2

You don't need a script. Use cp -R for recursive copy:

cp -R source_path dest_path

To do a recursive copy while preserving file attributes like last modified time etc., use the -p option as well:

cp -Rp source_path dest_path

From man cp:

 -R

If source_file designates a directory, cp copies the directory and the entire subtree connected at that point. If the source_file ends in a /, the contents of the directory are copied rather than the directory itself. This option also causes symbolic links to be copied, rather than indirected through, and for cp to create special files rather than copying them as normal files. Created directories have the same mode as the corresponding source directory, unmodified by the process' umask.

codeforester
  • 39,467
  • 16
  • 112
  • 140
0

It sounds like you want to copy a single file into all the subdirectories under the target directory (and into the target directory itself). If that is correct, then:

find $targetdir -type d -exec cp $sourcefile {} \;
Jack
  • 5,801
  • 1
  • 15
  • 20