1

I'm trying to find out whether a file is an image or not and then do something according to the result.This works fine for file in the present working directory and in other directories:

file -ib "$i" | grep "image/"

But this only works with files in the present directory (where the script was called from)

TEST=$(file -ib "$i" | grep "image/")

if [ "$TEST" == "" ]
then
    echo "Image"
else
    echo "Not an image"
fi

So something like ../../my.jpg works in the first case, but always gives "Not an image" in the second case. I would like to use my script on files anywhere on the system.

Thanks for your help.

6
  • 1
    What does bash -x second-fragment.sh show as the value in $TEST? That'll tell you what you need to do to fix the problem. Commented Aug 18, 2015 at 17:45
  • 1
    I assume you are setting i=$1 or similar in the script case? Commented Aug 18, 2015 at 17:45
  • 2
    You seem to have your condition wrong. TEST will be empty if grep doesn't find image. Commented Aug 18, 2015 at 17:53
  • Do you need the value of TEST later? If not you can do the command directly in the if Commented Aug 18, 2015 at 18:03
  • Let me try to explain a little better: Commented Aug 18, 2015 at 18:26

2 Answers 2

1

Please try:

path="path/to/images/folder"
for i in $(find $path -type f); do
  file -ib "$i" | grep -q "image/" && echo "$i: Image" || echo "$i: Not an image";
done
Sign up to request clarification or add additional context in comments.

Comments

0

Try:

TEST=$(file -i "$i" | grep ': *image/')

if [ "$TEST" = "" ];then 
  echo "not an image"
else 
  echo "it is an image"
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.