3

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

1

2 Answers 2

8

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.

5
  • 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.
    – kos
    Jan 14, 2016 at 15:02
  • nice, i'll need to commit this to memory
    – squareborg
    Jan 14, 2016 at 15:03
  • and how to include hidden files and dirs/
    – vico
    Jan 14, 2016 at 15:05
  • 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? Jan 14, 2016 at 15:10
  • @vico There's another shell option called dotglob for that. I've added notes against the various methods.
    – Oli
    Jan 14, 2016 at 15:19
0

what about:

cd ~/MYDIR
mv DIR* file* DESTINATIONDIR

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .