如何在shell中使用curl检查内容类型

时间:2017-09-27 07:46:23

标签: bash shell http curl

我想检查服务器中文件的内容类型。 以下代码总是回响"图像大小无效"。

    TYPE=$(curl -sI $IMAGE_LINK | grep Content-Type)
    IFS=" "
    set $TYPE
    echo $2

    if [ $2 == "image/gif" ] 
    then
        echo "image size is valid"
        exit 0  
    else
        echo "image size is invalid"
        exit 1
    fi  

这是输出。当$ 2是" image / gif"?时,为什么比较不起作用?

image/gif
image size is invalid

此外, 这是我不需要的解决方案。

    TYPE=$(curl -sI $IMAGE_LINK | grep "Content-Type: image/gif")
    echo $TYPE

    if [ ! "$TYPE" = "" ]

3 个答案:

答案 0 :(得分:1)

而不是grepIFSset等,您可以使用一个awk来提取Content-Type标题:

type=$(curl -sI "$IMAGE_LINK" | awk -F ': ' '$1 == "Content-Type" { print $2 }')

if [[ $type == *"image/gif"* ]] 
then
    echo "image size is valid"
    exit 0  
else
    echo "image size is invalid"
    exit 1
fi  

答案 1 :(得分:1)

比较不起作用,因为$2末尾有一个尾随回车符。如果你这样做,你可以看到它:

TYPE=$(curl -sI $IMAGE_LINK | grep Content-Type)
IFS=" "
set $TYPE
echo -n "$2" | od -t c

将产生:

0000000    i   m   a   g   e   /   g   i   f  \r
0000012

此外,由于空间包含在默认的IFS设置中,因此设置IFS并不能帮助您。您可以将IFS设置为包含回车符(IFS=$' \r'),或使用其他方式解析您需要的位:

TYPE=$(curl -sI "$IMAGE_LINK" | grep Content-Type | tr -d '\r' | cut -f 2 -d ' ')
if [ "$TYPE" = "image/gif" ]
then
    echo 'It works!'
fi

或者,甚至更好(正如@DanielStenberg所建议的那样):

TYPE=$(curl -sI "$IMAGE_LINK" -w '%{content_type}' -o /dev/null)
if [ "$TYPE" = "image/gif" ]
then
    echo 'It works!'
fi

答案 2 :(得分:1)

只需使用curl和-w option即可完成Content-Type:标题的提取,就像在这个shell脚本中一样:

type=$(curl -sI "$IMAGE_LINK" -o/dev/null -w '%{content_type}\n')

if [ "$type" = "image/gif" ]
then
    echo "image type is valid"
    exit 0  
else
    echo "image type is invalid"
    exit 1
fi
相关问题