I'm trying to write a script that runs on startup and copies any files on any attached USB drive to a specific directory but without the containing directories.

So i have a USB drive called Data, on data there is a 2 directories, Dir1 & Dir2, in each directory there is a file. Dir1File.txt and Dir2File.txt.

I want to copy the two files to /home/data but if i run

rsync -av /media/* /home/data

data then has a directory called Data, inside which are Dir1 & Dir 2 inside which are the respective files. Can this be done?


You could use the find command to get a list of all files and then use a loop to copy the files one by one. Something like this:

for i in `find /media -type f` ; do cp $i /home/data/ ; done

Of course, if the same filename appears in several places then that file will be overwritten and you will just get the last one.

Edit: it is probably better to do the copying already as part of the find command instead of using a loop, as described in the comment by steeldriver below.

  • 6
    find /media -type f -exec cp -t /home/data/ {} + would likely be more efficient - and wouldn't error out on any filenames with spaces in them. See Why is looping over find's output bad practice?. You can add -n (--no-clobber) or --backup=numbered to cp if you want to avoid overwriting existing files. – steeldriver Aug 6 at 20:28

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.