0

I found this script by Bruno that flattens a directory. Can someone tell me how to modify it to run it as loop so it would work on all directories within a specified (higher level) directory?
Thank you in advance ;)

# This scripts flattens the file directory
# Run this script with a folder as parameter:
# $ path/to/script path/to/folder

#!/bin/bash

rmEmptyDirs(){
    local DIR="$1"
    for dir in "$DIR"/*/
    do
        [ -d "${dir}" ] || continue # if not a directory, skip
        dir=${dir%*/}
        if [ "$(ls -A "$dir")" ]; then
            rmEmptyDirs "$dir"
        else
            rmdir "$dir"
        fi
    done }

flattenDir(){
    local DIR="$1"
    find "$DIR" -mindepth 2 -type f -exec mv -i '{}' "$DIR" ';' }

flattenDir "$1" rmEmptyDirs "$1" echo "Done"
2

Just one line will move all files (in child subdirs) to pwd.

$ find  . -mindepth 2 -type f -exec mv {} .. \;

This will move all regular files including dot-files (start with a dot) but not links.

Then, remove empty dirs:

$ find . -type d -empty -delete

Whatever is left out contains links (or other types of files) not moved.

1

One way to perform a certain operation all directories found within a given directory, is

setopt -s nullglob
for e in SPECIFIED_DIRECTORY/*
do
  setopt -u nullglob
  [[ -d $e ]] && YOUR_SCRIPT "$e"
done

Note that this will skip directories where the name starts with a dot. This is usually what we want, but if you want to include those directories as well, you can adapt my solution to this case too: See the dotglob option in the man page, and don't forget to exclude the special directories . and ...

Another possibilitiy is to use something like

find SPECIFIED_DIRECTORY -maxdepth 1 -type d -exec YOUR_SCRIPT {} \;
  • Thank you user1934428. How would I change your script to run YOUR script in CURRENT directory instead SPECIFIED_DIRECTORY? – Steven D Jul 4 '18 at 15:33
  • The current directory (I guess you mean: working directory) can be denoted by a single period (.) or by using the shell variable PWD ($PWD). – user1934428 Jul 9 '18 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.