Move all files and directories to destination directory
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.
Related videos on Youtube
vico
Updated on September 18, 2022Comments
-
vico over 1 year
I have directory structure:
~/MYDIR/ /DESTINATIONDIR/ /DIR1/ /DIR2/ /file1 /file2
I need to move
DIR1, DIR2,file1,file2
toDESTINATIONDIR
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
-
Dimitri Podborski over 8 yearsPossible duplicate of Moving folder and subfolder to another path
-
-
kos over 8 yearsSide 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 simplymv -t ~/MYDIR/DESTINATIONDIR ~/MYDIR/!(DESTINATIONDIR)
will likely avail. -
squareborg over 8 yearsnice, i'll need to commit this to memory
-
vico over 8 yearsand how to include hidden files and dirs/
-
Dimitri Podborski over 8 yearsdo 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 over 8 years@vico There's another shell option called
dotglob
for that. I've added notes against the various methods.