title: BASH loop through folders and files
body: <p>I have a problem with listing through directories. I wanted to make script which will loop through dirs and files in them so I can move them elsewhere.</p>
  
  <p>My problem is that I need to SORT all the files within the folders. There's like 2000 directories and I need to loop through them and then loop through all files within these dirs and sort them by extension in directory which will be created (or files will be moved) and it's name will be that particular extension </p>
  
  <p>Could anyone help?</p>
  
  <pre><code>#!/bin/bash
  
  tar_fol="$HOME/Desktop/try/"
  to_fol="$HOME/Desktop/SortedFiles/"
  
  for DIRE in "$(ls -d  $tar_fol"*")"
  do
  
    echo "Checking dir : $DIRE"
  
    for FIL in "$(ls -p $tar_fol$DIRE)"
    do
      echo "Checking file : $FIL"
  
      if [ "$(find ~/Desktop/ -type d -name ${FIL##*.})" != "" ]
        then
            mv -f $tar_fol$FIL $to_fol${FIL##*.}
        else
          mkdir $to_fol${FIL##*.}
          mv $tar_fol$FIL $to_fol${FIL##*.}
        fi
  
    done
  done
  </code></pre>