I have one directory with many sub-directories. All of those sub-directories contain files which each have unique names. I want to take all the files from all of the sub-directories and move them all to one directory.

There are a few hundred sub-directories, so I wouldn't want to do this by hand. How would I go about writing a shell script to do this? I'm using bash.

3 Answers 3


find is the solution:

find /srcpath -type f -exec mv {} /dstpath \;

or better, if your mv has the -t destination-dir option:

find /srcpath -type f -exec mv -t /dstpath {} +

The simple way, if there's a single level of subdirectories:

cd source_directory
mv -- */* /path/to/target/directory

If you want to move the files to the parent directory, that's mv -- */* .. Note that files or directories whose name begins with . (“dot files”) are excluded. To include them, in bash, run shopt -s dotglob first. In zsh, run setopt glob_dots first.

If you want to move files from subsubdirectories and so on recursively as well, with zsh:

cd source_directory
mv -- */**/*(^/) .

If you try to run the mv command and get an error like “command line too long”, you'll have to break it down. The simplest way is to use find. With GNU tools (non-embedded Linux and Cygwin):

find source_directory -mindepth 2 ! -type d \
  -exec mv -t /path/to/target/directory -- {} +
  • Mucking around with mv in a situation like this is not a terribly useful idea since it'll cheerfully move subdirectories, content and all.
    – Shadur
    Aug 13, 2013 at 12:10
  • @Shadur mv will only move subdirectories if it's passed subdirectories, which doesn't happen here (after Stephane's fix). Aug 13, 2013 at 12:13
#! /bin/sh

# set your output directory here

# get a list of all the files (-type f)
# in subdirectories (-mindepth 1)
# who do not match the outdir  (-path $outdir -prune)
# and step through and execute a move
find . -mindepth 1 -path $outdir -prune -o -type f -exec mv '{}' $outdir \;

This will allow you to search from the present working directory, all the sub directories, and move the files to a sub directory in the same working directory ($outdir) - note the proceeding ./ on the path to make the -prune work properly.

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.