Using for loop to move files from subdirectories to parent directories

11,982

Small change. change

subs=ls $dir1

to

subs=`ls $dir1`

Notice the backquotes. Backquotes actually execute the bash command and return the result. If you issue echo $subs after the line, you'll find that it correctly lists folder1, folder2.

Second small change is to remove double quotes in the mv command. Change them to

mv $dir1/$i/*/* $dir1/$i

Double quotes take literal file names while removing quotes takes the recursive directory pattern.

After that, your initial for loop is indeed correct. It will move everything from sub1 and sub2 to folder1 etc.

Share:
11,982
dayne
Author by

dayne

Please see my personal website for more info and contact information.

Updated on June 04, 2022

Comments

  • dayne
    dayne almost 2 years

    I just made the switch to linux and I am trying to write my first bash script. I have a folder that contains numerous folders, all with subfolders containing files. Something like:

    • MainFolder

      • Folder1
        • Sub1 (Contains many files)
        • Sub2 (Contains many files)
      • Folder2
        • Sub1 (Contains many files)
        • Sub2 (Contains many files)

      . . .

    I want to move all the files contained in the sub-folders to the their parent folders. My first instinct is to try and write a for-loop. I was able to do one folder at a time with the command:

    mv MainFolder/Folder1/*/* MainFolder/Folder1/
    

    But I was hoping to write a bash script to loop over all the folders in the main directory. Here is what I have so far:

    #!/bin/bash
    
    dir1="/pathto/MainFolder"
    
    subs= ls $dir1
    
    for i in $subs; do
      mv "$dir1/$i/*/*" "$dir1/$i/" 
    done
    

    This, obviously, does not work, but I do not understand where I am going wrong.

    I also tried:

    mv MainFolder/*/*/* MainFolder/*/
    

    with pretty disastrous results. Once I get the file move working properly, I would also like to delete the old sub folders within the loop.

  • giammi56
    giammi56 about 2 years
    /store/media" should be removed and the script run at the same level of the sub folders
  • user2514157
    user2514157 almost 2 years
    Processing "ls" in the manner described by the accepted answer introduces pitfalls, including choking on directory names that contain spaces. See, e.g., mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.2‌​9 AND superuser.com/questions/1191472/…