I have created a script that will create a few directories and then organize other files from one directory by moving them into specific sub-directories based on their extension (i.e. .gif in media, .jpg in pictures).

Now I have to check those directories to make sure they contain only those files with the proper extension.

Below is what I've come up with so far with comments explaining where I'm going with this:


    #iterate over each DIRECTORY once
    #while in DIRECTORY list the files it contains
    #check the extension of containe files with given list of EXTENSIONS
    #if file has wrong extension print error message and stop loop
    #if all files are in corret DIRECTORY print confirmation message

    echo "Checking: $DIRECTORY for:$EXTENSIONS"

    for (( i = 0; i < 4; i++ )); do
        if [[ i -eq 1 ]]; then
            EXTENSIONS="*.txt *.doc *.docx"
            #list files and check EXTENSIONS
    elif [[ i -eq 2 ]]; then
            #if I equals 2 then look into media DIRECTORY
            #list files and check EXTENSIONS
    elif [[ i -eq 3 ]]; then
            EXTENSIONS="*.jpg *.jpeg"
            #if I quals 3 then look into pictures DIRECTORY
            #list files and check EXTENSIONS
  • Note that file "extensions" don't necessarily mean anything, they're as arbitrary as the rest of the filename. e.g. a jpeg or text file could be named foo.gif. If you want to be certain that the correct file types are in the correct directories, use file --mime-type and test for image/gif, image/jpeg, text/plain, application/msword etc.
    – cas
    Apr 15 '16 at 1:35
  • Sounds quite like a typical use case for the exiftool
    – techraf
    Apr 15 '16 at 3:10
  • By the way, your original file organizing script can probably be replaced by a couple find commands similar to the ones in my answer below.
    – Wildcard
    Apr 15 '16 at 3:34

How about you just print all the files that don't match your extensions?

find documents -type f ! \( -name \*.txt -o -name \*.doc -o -name \*.docx \)
find media     -type f !    -name \*.gif
find pictures  -type f ! \( -name \*.jpg -o -name \*.jpeg \)

Why do you need to check other at all if anything is allowed in there?

By the way, Unix convention is: "no output = good news". So the above commands just print files that don't match the extensions specified; if all is well they won't print anything.

P.S.: This is a good example of the evolution of a programmer. ;)

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.