48

How to copy only the regular files in a directory (ignoring sub-directories and links) to the same destination? (bash on Linux) A very large number of files

3
  • 4
    How is this off topic? I really hate this part of stackoverflow. Commented Mar 17, 2019 at 18:56
  • I suspect the rational is that this should go to something like Super User, which I kind of understand, but also this is a legit bash programming question. Commented Mar 21, 2019 at 14:26
  • can you rephrase the headline...this is how to copy, not how to list Commented Sep 11, 2019 at 17:24

3 Answers 3

77
for file in /source/directory/*
do
    if [[ -f $file ]]; then
        #copy stuff ....
    fi
done
Sign up to request clarification or add additional context in comments.

3 Comments

It also won't respect files with whitespace in the name.
@holygeek: No, globbing (pathname expansion) is not subject to the ARG_MAX max. command-line length limitation, because there is no external utility involved. That said, any loop with a large number of iterations in Bash will be slow.
@glennjackman: Filenames with whitespace are handled correctly, due to use of [[ ... ]] rather than [ ... ]; [[ ... ]] doesn't require double-quoting variable references (in most cases).
29

To list regular files in /my/sourcedir/, not looking recursively in subdirs:

find /my/sourcedir/ -type f -maxdepth 1

To copy these files to /my/destination/:

find /my/sourcedir/ -type f -maxdepth 1 -exec cp {} /my/destination/ \;

1 Comment

Thanks :). I'd to add * to get list of all files inside sourcedir. find /data/* -maxdepth 2 -type f
9

To expand on poplitea's answer, you don't have to exec cp for each file: use xargs to copy multiple files at a time:

find /my/sourcedir -maxdepth 1 -type f -print0 | xargs -0 cp -t /my/destination

or

find /my/sourcedir -maxdepth 1 -type f -exec cp -t /my/destination '{}' +

1 Comment

-exec ... + is the most efficient solution; one thing worth mentioning: cp -t is a GNU extension.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.