Copy a file into all subfolders and subsubfolders.

I have a file say, a.txt

I want to copy it to all subfolders and all the folders within those folders. I have tried creating a script to run this, but I keeping getting errors.

Any help?

the code i was trying was below. But this only copies it into subdirectories, not subsubdirectories

for i in ./* # iterate over all files in current dir
    if [ -d "$i" ] # if it's a directory
        cp a.txt "$i" # copy a.txt into it
        cd ..
  • 1
    To better help some more information is needed. What OS are you running the script on? can you post the script you have and what error you are gettings? – grag42 Apr 23 '15 at 18:29
  • linux. i edited question – Jackson Hart Apr 23 '15 at 18:37

Your script only copies into subdirectories because that's all you are telling it to do (./* is all files in current directory, and you never go any deeper). You could implement it recursively, but it's probably easier to just do something like:

find . -mindepth 1 -type d -exec cp a.txt {} \;

Or, for POSIX compliance and maximum portability:

find . ! -path . -type d -exec cp a.txt {} \;

That will do what you want: copy a.txt to every (sub)+directory in the current tree.

You can use the -maxdepth option to limit the depth of subdirectories if you want. You can use the -mindepth option (where available) to set a minimum depth limit. In the first example above we use -mindepth 1 to skip . to avoid outputting a warning about copying a file onto itself -- it's not absolutely necessary but it's nice to not have warnings.

For more information about find check out its man page.

  • When I Do that I get: cp: a.txt' and ./a.txt' are the same file – Jackson Hart Apr 23 '15 at 18:46
  • @user440178 Yes, you would get that from the . returned by find. It is an easy problem to diagnose, if you spend a second playing with find you can readily see that it outputs .. The operation still succeeds just fine. If the warning bothers you, use the info here to construct a solution without the warning. – Jason C Apr 23 '15 at 18:50
  • Is there a way to make it only go in subsubfolders and not subfolders? – Jackson Hart Apr 23 '15 at 18:52
  • I'm not sure that it's working, it just is hanging for a while – Jackson Hart Apr 23 '15 at 18:53
  • @user440178 "Is there a way to make it only go in subsubfolders and not subfolders?" When you read the post I linked to and saw the -mindepth option, did you discover your own answer to this question? – Jason C Apr 23 '15 at 18:54

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.