在shell脚本中测试文件格式

时间:2012-04-25 21:56:21

标签: shell file-format

我想要的是这个脚本测试作为参数传递给它的文件是ASCII文件还是zip文件,如果它是ascii echo“ascii”,如果它是一个zip echo“zip”,否则echo “ERROR”。

这就是我现在所拥有的

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 

2 个答案:

答案 0 :(得分:3)

运行file / grep命令并检查其返回代码的方式不正确。你需要做这样的事情:

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

之前,您正在将文件/ grep管道的文本输出捕获到变量中,然后将其与数字0作为字符串进行比较。以上将使用命令的实际返回值,这是您需要的。

答案 1 :(得分: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
相关问题