Move all files and directories to destination directory

8,698

There are three ways I'd consider doing this.

Hacky and error-fuelled, "MOVE ALL THE THINGS"

mv ~/MYDIR/* ~/MYDIR/DESTINATIONDIR

This will try to move the destination into itself and will explode:

mv: cannot move ‘~/MYDIR/DESTINATIONDIR’ to a subdirectory of itself, ‘~/MYDIR/DESTINATIONDIR/DESTINATIONDIR’

But it will move [almost] everything else. So it works but it's a bit of a mess. If you need to match hidden files, run shopt -s dotglob beforehand and it'll work.

Moving a list of files manually

Given the short list of things, we can quite easily just list them out with a little bash expansion:

 mv ~/MYDIR/{DIR{1,2},file{1,2}} ~/MYDIR/DESTINATIONDIR

If you need hidden files with this method, just include them in the list.

If this list is coming from something else (eg find) it can be tough to ensure the destination is the last argument. You can move the destination to the front with the -t argument. This is a horrible example but highlights when you need it:

find ~/MYDIR/ -maxdepth 1 ! -name DESTINATIONDIR -exec mv -t ~/MYDIR/DESTINATIONDIR {} +

Inverse globbing with shopt, elegance defined.

So let's strike the balance between manually listing and wildcards. By turning on the extended globbing features in Bash, we can select [almost] everything but the destination directory.

shopt -s extglob
mv ~/MYDIR/!(DESTINATIONDIR) ~/MYDIR/DESTINATIONDIR

If you need to match hidden files, run shopt -s dotglob beforehand and it'll work.

Share:
8,698

Related videos on Youtube

vico
Author by

vico

Updated on September 18, 2022

Comments

  • vico
    vico over 1 year

    I have directory structure:

    ~/MYDIR/
      /DESTINATIONDIR/
      /DIR1/
      /DIR2/
      /file1
      /file2
    

    I need to move DIR1, DIR2,file1,file2 to DESTINATIONDIR

    What is most elegant and optimal way to do this from terminal?

    UPD: asume that we have much more files and dirs with different names

  • kos
    kos over 8 years
    Side note, I've always had extglob turned on by default in interactive shells since Trusty, so unless the command is to be used in a script simply mv -t ~/MYDIR/DESTINATIONDIR ~/MYDIR/!(DESTINATIONDIR) will likely avail.
  • squareborg
    squareborg over 8 years
    nice, i'll need to commit this to memory
  • vico
    vico over 8 years
    and how to include hidden files and dirs/
  • Dimitri Podborski
    Dimitri Podborski over 8 years
    do I really need to select everything but the destination dir? Can't I just do mv * destination even if destination is in the same directory. mv will not move the destination dir and will just inform you that this is not possible. right?
  • Oli
    Oli over 8 years
    @vico There's another shell option called dotglob for that. I've added notes against the various methods.