Looping through directories in Bash

I require the script to cd to a directory, then delete all but a few files in sub-directories—but leave the folders alone. Would it help to use switch/cases for each file I need to preserve?

Ideally, I think it should keep searching for further sub-dirs, instead of me having nested loops which only search down two levels.

Another problem is that it skips folders with spaces (though this isn’t an issue with the volumes that the script will run, for now).

Here’s my code:

for i in /Users/YourName/Desktop/Test/* ; do
  if [ -d "$i" ]; then
    cd $i

    for j in "$i"/* ; do
      if [ -d "$j" ]; then
        cd $j

        for k in $(ls *); do
          if [ ! $k == "watch.log" ]; then
            echo $k
            rm -rf $k
          fi
        done

      fi
    done

  fi
done
12
задан codeforester 8 May 2018 в 16:43
поделиться