Search code examples
shellfile-format

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 

Solution

  • 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