EN
Bash - detect PNG, JPG, GIF file using file bytes (magic numbers in file)
10 points
In this short article, we would like to show how in Bash, detect PNG, JPG, or GIF files when we don't know file extension - that king of detection uses magic numbers located inside the file).
Quick solutions (use the following commands):
1. JPEG file test:
xxxxxxxxxx
1
[ "$(xxd -s 6 -l 4 -p "/path/to/image.jpg")" = "4a464946" ] && echo "is JPEG" || echo "is not JPEG"
2. PNG file test:
xxxxxxxxxx
1
[ "$(xxd -s 1 -l 3 -p "/path/to/image.png")" = "504e47" ] && echo "is PNG" || echo "is not PNG"
3. GIF file test:
xxxxxxxxxx
1
[ "$(xxd -s 0 -l 3 -p "/path/to/image.gif")" = "474946" ] && echo "is GIF" || echo "is not GIF"
Example detect_image_type.sh
file content:
xxxxxxxxxx
1
2
3
function is_jpg() # args: file_path
4
{
5
# J F I F (as chars)
6
# 4a464946 (in hex)
7
[ "$(xxd -s 6 -l 4 -p "$1")" = "4a464946" ] && return 0 || return 1
8
}
9
10
function is_png() # args: file_path
11
{
12
# P N G (as chars)
13
# 504e47 (in hex)
14
[ "$(xxd -s 1 -l 3 -p "$1")" = "504e47" ] && return 0 || return 1
15
}
16
17
function is_gif() # args: file_path
18
{
19
# G I F (as chars)
20
# 474946 (in hex)
21
[ "$(xxd -s 0 -l 3 -p "$1")" = "474946" ] && return 0 || return 1
22
}
23
24
25
# Usage example:
26
27
echo -e "\n--------------------------------\nJPG files:\n";
28
for file_name in *.*
29
do
30
is_jpg "$file_name" && echo "$file_name"
31
done
32
33
34
echo -e "\n--------------------------------\nPNG files:\n";
35
for file_name in *.*
36
do
37
is_png "$file_name" && echo "$file_name"
38
done
39
40
41
echo -e "\n--------------------------------\nGIF files:\n";
42
for file_name in *.*
43
do
44
is_gif "$file_name" && echo "$file_name"
45
done
46
47
48
echo -e "\n--------------------------------\n"
49
echo -e "DONE!\n"
Running:
xxxxxxxxxx
1
./detect_image_type.sh
Example output:
xxxxxxxxxx
1
--------------------------------
2
JPG files:
3
4
picture.jpg
5
mountains.jpeg
6
river.tmp
7
sun.tmp
8
9
--------------------------------
10
PNG files:
11
12
ball.png
13
square.unknown
14
15
--------------------------------
16
GIF files:
17
18
animation.dat
19
20
--------------------------------
21
DONE!