Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - How to loop through sub directories and copy in a file

Tags:

bash

unix

copy

I'm new to coding in bash.

I'm trying to create something which will loop through all subdirectories, and within each one it should copy a file to that directory.

So for example, if I have the following directories

/dir1/  
/dir2/  
/dir3/  
...  
...  
/dirX/

And a file fileToCopy.txt

Then I want to run something which will open every single /dirX file and put fileToCopy.txt in that directory. Leaving me with:

/dir1/fileToCopy.txt
/dir2/fileToCopy.txt
/dir3/fileToCopy.txt
...
...
/dirX/fileToCopy.txt

I would like to do this in a loop, as then I am going to try to modify this loop to add some more steps, as ultimately the .txt file is actually a .java file, I am wanting to copy it into each directory, compile it (with the other classes in there), and run it to gather the output.

Thanks.

like image 440
ThePerson Avatar asked Jan 24 '26 09:01

ThePerson


2 Answers

for i in dir1, dir2, dir3, .., dirN
    do
        cp /home/user1068470/fileToCopy.txt $i
    done

Alternatively, you can use the following code.

for i in *
    do                 # Line breaks are important
        if [ -d $i ]   # Spaces are important
            then
                cp fileToCopy.txt $i
        fi
    done
like image 109
asenovm Avatar answered Jan 25 '26 23:01

asenovm


Finds all directory under the current directory (.) and copies the file into them:

find . -type d -exec cp fileToCopy.txt '{}' \;
like image 35
Guru Avatar answered Jan 25 '26 23:01

Guru