如何在脚本中检查文件类型

ajr*_*dev 5 file-command shell-script files

我想对目录中的所有图像进行循环。图像没有扩展名,所以我必须读取图像的第一个字节才能知道它的类型。循环最终应该是这样的。

for file in *
do
    if [ file --mime-type -b ]
    then
        ***
    fi
done
Run Code Online (Sandbox Code Playgroud)

Gil*_*not 7

使用case语句和命令替换

for file in *; do
    case $(file --mime-type -b "$file") in
        image/*g)        ... ;;
        text/plain)      ... ;;
        application/xml) ... ;;
        application/zip) ... ;;
        *)               ... ;;
    esac
done
Run Code Online (Sandbox Code Playgroud)

检查:
http://mywiki.wooledge.org/BashFAQ/002
http://mywiki.wooledge.org/CommandSubstitution
http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Choices
HTTP://wiki.bash-hackers .org/syntax/ccmd/case

编辑

如果您坚持不使用caseif使用的语句:

if [[ $(file --mime-type -b "$file") == image/*g ]]; then
...
else
...
fi 
Run Code Online (Sandbox Code Playgroud)