Using for loop to move files from subdirectories to parent directories Using for loop to move files from subdirectories to parent directories unix unix

Using for loop to move files from subdirectories to parent directories


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.


!/bin/bash

dir1="/pathto/MainFolder"

subs=ls $dir1

for i in $subs; do

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

done


Yes - this is working solution

#!/bin/bashmainDir="$(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"    fidone