2

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 
4

2 に答える 2

3

file/grep コマンドを実行してリターン コードを確認する方法が正しくありません。次のようなことをする必要があります:

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

以前は、file/grep パイプラインのテキスト出力を変数にキャプチャし、それを文字列として数値 0 と比較していました。上記は、必要なものであるコマンドの実際の戻り値を使用します。

于 2012-04-25T22:04:07.020 に答える
2

fileコマンドについては、 を試してください-b --mime-type。MIME タイプでのフィルタリングの例を次に示します。

#!/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
于 2012-05-11T15:04:22.497 に答える