dayne
dayne

Reputation: 7784

Using for loop to move files from subdirectories to parent directories

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:

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.

Upvotes: 4

Views: 16802

Answers (3)

yaroslawww
yaroslawww

Reputation: 1088

Yes - this is working solution

#!/bin/bash

mainDir="$(dirname $(realpath $0))/store/media"

subs=`ls $mainDir`

for i in $subs; do
    if [[ -d "$mainDir/$i" ]]; then
        mv "$mainDir/$i"/* "$mainDir/"
        rm -rf "$mainDir/$i"
    fi
done

Upvotes: 1

Marietto
Marietto

Reputation: 161

!/bin/bash

dir1="/pathto/MainFolder"

subs=ls $dir1

for i in $subs; do

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

done

Upvotes: 0

Sudeep Juvekar
Sudeep Juvekar

Reputation: 5068

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.

Upvotes: 5

Related Questions