5

I want to do a loop for all the images in a directory. The images doesn't have extension so I have to read the first bytes of the image to know its type. The loop should end up being something like.

for file in *
do
    if [ file --mime-type -b ]
    then
        ***
    fi
done

1 Answer 1

6

Using the case statement and command substitution :

for file in *; do
    case $(file --mime-type -b "$file") in
        image/*g)        ... ;;
        text/plain)      ... ;;
        application/xml) ... ;;
        application/zip) ... ;;
        *)               ... ;;
    esac
done

Check :
http://mywiki.wooledge.org/BashFAQ/002
http://mywiki.wooledge.org/CommandSubstitution
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Choices
http://wiki.bash-hackers.org/syntax/ccmd/case

EDIT

if you insist to don't use case but an if statement using :

if [[ $(file --mime-type -b "$file") == image/*g ]]; then
...
else
...
fi 
2
  • 1
    How would it be with the if statement? if (($(file --mime-type -b file) == "image/*g"))
    – user96101
    Dec 27, 2014 at 18:17
  • POST edited accordingly Dec 27, 2014 at 18:41

Your Answer

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