Top Nav

Archive | Bash Scripting

Copy Files & Create Missing Directories

I needed to find all the image files in a large directory tree and then copy them to a new directory tree while preserving the directory structure. Here’s my solution:

1. Find the files and save list to a file:

This command demonstrates using the -exec option on “find” to feed the “file” command.

2. Copy each file on the list, creating sub directories as needed:

This command demonstrates a one line while loop feed by input redirection. Also notice the “–parents” option on the “cp” command.


Bash Loops

Here’s a basic loop in Bash:

Notice that it iterates over a space delimited string of values.

If you have a comma delimited list then you can do something like this:

IFS is the “internal field separator” which defaults to a blank space. We save the original IFS and change it to a comma. Then once we’re done we restore the original IFS.

Here are some links to additional examples: