スクリプトでファイルの種類を確認する方法

スクリプトでファイルの種類を確認する方法

ディレクトリ内のすべての画像を繰り返したいです。イメージには拡張子がないため、そのタイプを知るにはイメージの最初のバイトを読み取る必要があります。ループは次のようになります。

for file in *
do
    if [ file --mime-type -b ]
    then
        ***
    fi
done

ベストアンサー1

このcaseドアを使用してコマンドの置き換え:

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

確認する:
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

編集する

使用しないと主張してcase使用ifすると宣言する場合:

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

おすすめ記事