Reputation: 559
I want to check content type of a file in a server. Following code always echoes "image size is invalid".
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
This is the output. Why comparison does not work when $2 is "image/gif"?
image/gif
image size is invalid
Additionally, This is my unwanted solution.
TYPE=$(curl -sI $IMAGE_LINK | grep "Content-Type: image/gif")
echo $TYPE
if [ ! "$TYPE" = "" ]
Upvotes: 1
Views: 1352
Reputation: 47032
The comparison doesn't work because there is a trailing carriage return at the end of $2
. You can see it if you do this:
TYPE=$(curl -sI $IMAGE_LINK | grep Content-Type)
IFS=" "
set $TYPE
echo -n "$2" | od -t c
Which will yield:
0000000 i m a g e / g i f \r
0000012
Also, setting IFS isn't really helping you here since space is included in the default IFS setting. You could set IFS to include the carriage return (IFS=$' \r'
), or use another way to parse out the bit you need:
TYPE=$(curl -sI "$IMAGE_LINK" | grep Content-Type | tr -d '\r' | cut -f 2 -d ' ')
if [ "$TYPE" = "image/gif" ]
then
echo 'It works!'
fi
Or, even better (as suggested by @DanielStenberg):
TYPE=$(curl -sI "$IMAGE_LINK" -w '%{content_type}' -o /dev/null)
if [ "$TYPE" = "image/gif" ]
then
echo 'It works!'
fi
Upvotes: 1
Reputation: 58014
Extracting the Content-Type:
header can be done with just curl and the -w option, like in this shell script:
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
Upvotes: 7
Reputation: 785156
Instead of grep
and IFS
, set
etc, you can use a single awk
to extract Content-Type
header:
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
Upvotes: 2