Saturday, June 4, 2022

[SOLVED] Using for loop to move files from subdirectories to parent directories

Issue

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.


Solution

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.



Answered By - Sudeep Juvekar
Answer Checked By - David Goodson (WPSolving Volunteer)