josephino
josephino

Reputation: 360

Testing file formats in a shell script

What I want is for this script to test if a file passed to it as a parameter is an ASCII file or a zip file, if it's an ascii echo "ascii", if it's a zip echo "zip", otherwise echo "ERROR".

Here's what I have at the moment

filetype = file $1
isAscii=`file $1 | grep -i "ascii"`
isZip=`file $1 | grep -i "zip"`

if [ $isAscii -gt "0" ] then echo "ascii";
else if [ $isZip -gt "0" ] then echo "zip";
else echo "ERROR";
fi 

Upvotes: 2

Views: 1782

Answers (2)

Rony
Rony

Reputation: 1734

For the file command, try -b --mime-type. Here is an example of filtering on MIME types:

#!/bin/sh
type file || exit 1
for f; do
    case $(file -b --mime-type "$f") in
        text/plain)
            printf "$f is ascii\n"
            ;;
        application/zip)
            printf "$f is zip\n"
            ;;
        *)
            printf "ERROR\n"
            ;;
    esac
done

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249444

The way you are running the file/grep commands and checking their return codes is not right. You need to do something like this:

if file "$1" | grep -i ascii; then
    echo ascii
fi

Before, you were capturing the textual output of the file/grep pipeline into the variable and then comparing it with the number 0 as a string. The above will use the actual return value of the command, which is what you need.

Upvotes: 3

Related Questions