MAGIC(4)
π MAGIC(4) β file command's magic pattern file π
okay so bestie, this is the Kernel Interfaces Manual page for MAGIC(4), and it literally documents the format of magic files as used by file(1) version 5.47. file(1) figures out what type a file is usingβamong other testsβa test for whether the file contains certain βmagic patternsβ. iconic behavior π. The database of those βmagic patternsβ usually lives in a binary file at /usr/share/misc/magic.mgc or in a directory of source text magic pattern fragment files at /usr/share/misc/magic. That database specifies what patterns are to be tested for, what message or MIME type to print if a particular pattern is found, and additional information to extract from the file. no cap.
π NAME π
magic β the file command's magic pattern file π
β¨ DESCRIPTION β¨
So here's the format of the source fragment files used to build this database: every line of a fragment file specifies a test to be performed. A test compares the data starting at a particular offset in the file with a byte value, a string or a numeric value. If the test succeeds, a message is printed. The line consists of the following fields:
offset β a number specifying the offset (in bytes) into the file of the data which is to be tested. This offset can be a negative number if it is:
- the first direct offset of the magic entry (at continuation level
0), in which case it is interpreted as an offset from the end end of the file going backwards. This works only when a file descriptor to the file is available and it is a regular file. - a continuation offset relative to the end of the last up-level field (
&).
If the offset starts with the symbol +, then all offsets are interpreted as from the beginning of the file (the default).
type β the type of the data to be tested. The possible values are:
byteβ a one-byte value.shortβ a two-byte value in this machine's native byte order.longβ a four-byte value in this machine's native byte order.quadβ an eight-byte value in this machine's native byte order.floatβ a 32-bit single precision IEEE floating point number in this machine's native byte order.doubleβ a 64-bit double precision IEEE floating point number in this machine's native byte order.stringβ a string of bytes. The string type specification can be optionally followed by a/<width>option and optionally followed by a set of flags[bCcftTtWw]*. Slash characters can be used to separate options for readability. The width limits the number of characters to be copied. Zero means all characters. The following flags are supported:bβ force binary file test.Cβ use upper case insensitive matching: upper case characters in the magic match both lower and upper case characters in the target, whereas lower case characters in the magic only match upper case characters in the target. (not valid for regex)cβ use lower case insensitive matching: lower case characters in the magic match both lower and upper case characters in the target, whereas upper case characters in the magic only match upper case characters in the target. (not valid for regex) To do a complete case insensitive match, specify both βcβ and βCβ.fβ require that the matched string is a full word, not a partial word match.sβ don't include the match length in the offset computation. (only valid for search and regex)Tβ trim the string, i.e. leading and trailing whitespace is deleted before the string is printed.tβ force text file test.Wβ compact whitespace in the target, which must contain at least one whitespace character. (not valid for regex) If the magic hasnconsecutive blanks, the target needs at leastnconsecutive blanks to match.wβ treat every blank in the magic as an optional blank. (not valid for regex)
pstringβ a Pascal-style string where the firstbyte/short/intis interpreted as the unsigned length. The length defaults tobyteand can be specified as a modifier. The following modifiers are supported:Bβ a byte length (default).Hβ a 2 byte big endian length.hβ a 2 byte little endian length.Lβ a 4 byte big endian length.lβ a 4 byte little endian length.Jβ the length includes itself in its count.
The string is not NUL terminated. βJβ is used rather than the more valuable βIβ because this type of length is a feature of the JPEG format.
dateβ a four-byte value interpreted as a UNIX date.qdateβ an eight-byte value interpreted as a UNIX date.ldateβ a four-byte value interpreted as a UNIX-style date, but interpreted as local time rather than UTC.qldateβ an eight-byte value interpreted as a UNIX-style date, but interpreted as local time rather than UTC.qwdateβ an eight-byte value interpreted as a Windows-style date.msdosdateβ a two-byte value interpreted as FAT/DOS-style date.msdostimeβ a two-byte value interpreted as FAT/DOS-style time.beid3β a 32-bit ID3 length in big-endian byte order.beshortβ a two-byte value in big-endian byte order.belongβ a four-byte value in big-endian byte order.bequadβ an eight-byte value in big-endian byte order.befloatβ a 32-bit single precision IEEE floating point number in big-endian byte order.bedoubleβ a 64-bit double precision IEEE floating point number in big-endian byte order.bedateβ a four-byte value in big-endian byte order, interpreted as a Unix date.beqdateβ an eight-byte value in big-endian byte order, interpreted as a Unix date.beldateβ a four-byte value in big-endian byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.beqldateβ an eight-byte value in big-endian byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.beqwdateβ an eight-byte value in big-endian byte order, interpreted as a Windows-style date.bemsdosdateβ a two-byte value in big-endian byte order, interpreted as FAT/DOS-style date.bemsdostimeβ a two-byte value in big-endian byte order, interpreted as FAT/DOS-style time.bestring16β a two-byte unicode (UCS16) string in big-endian byte order.leid3β a 32-bit ID3 length in little-endian byte order.leshortβ a two-byte value in little-endian byte order.lelongβ a four-byte value in little-endian byte order.lequadβ an eight-byte value in little-endian byte order.lefloatβ a 32-bit single precision IEEE floating point number in little-endian byte order.ledoubleβ a 64-bit double precision IEEE floating point number in little-endian byte order.ledateβ a four-byte value in little-endian byte order, interpreted as a UNIX date.leqdateβ an eight-byte value in little-endian byte order, interpreted as a UNIX date.leldateβ a four-byte value in little-endian byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.leqldateβ an eight-byte value in little-endian byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.leqwdateβ an eight-byte value in little-endian byte order, interpreted as a Windows-style date.lemsdosdateβ a two-byte value in little-endian byte order, interpreted as FAT/DOS-style date.lemsdostimeβ a two-byte value in little-endian byte order, interpreted as FAT/DOS-style time.lestring16β a two-byte unicode (UCS16) string in little-endian byte order.melongβ a four-byte value in middle-endian (PDP-11) byte order.medateβ a four-byte value in middle-endian (PDP-11) byte order, interpreted as a UNIX date.meldateβ a four-byte value in middle-endian (PDP-11) byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.indirectβ starting at the given offset, consult the magic database again. The offset of the indirect magic is by default absolute in the file, but one can specify/rto indicate that the offset is relative from the beginning of the entry. π¦
Okay bestie, picking up right where we left offβhereβs the rest of the type lore, and itβs lowkey iconic π
nameβ Define a βnamedβ magic instance that otherusemagic entries can call, like a subroutine call. For named instances, direct magic offsets are relative to the offset of the previous matched entry, but indirect offsets are relative to the beginning of the file as usual. Named magic entries return true if there was a match while evaluating the entry, or if there was already a previous existing match. iykykuseβ Recursively call the named magic starting from the current offset. If the name of the referenced magic begins with a^, then the endianness is switched: say the magic mentionedleshort, it gets treated asbeshortand vice versa. This is super useful for not duplicating rules for different endianness. slayregexβ A regular expression match in extended POSIX regular expression syntax (likeegrep). The type spec can optionally be followed by/[c][s][l]. Thecflag makes the match case-insensitive, thesflag updates the offset to the start offset of the match (instead of the end), and thelmodifier changes the length limit to mean number of lines instead of a byte count. Lines are delimited by the platformβs native line delimiter. When you specify a line count, an implicit byte count is also computed assuming each line is 80 characters long. If neither a byte nor a line count is specified, the search is limited automatically to8KiB. Note:^and$match the beginning and end of individual lines, not the beginning and end of the file.
Heads up bestie: regexes can take exponential time to process and their performance is hard to predict, so their use is discouraged. In production environments, check their performance carefully. Also limit the size of the string to search by specifying /<length>, so you donβt get performance issues scanning long files.
searchβ A literal string search starting at the given offset. You can use the same modifier flags as for string patterns. The search expression must include the range in the form/number, i.e. the number of positions where the match will be attempted, starting from the start offset. Great for searching larger binary expressions with variable offsets, using\escapes for special characters. The order of the modifier and the number doesnβt matter. flexible much?defaultβ Meant to be used with the testx(which is always true) and it has no type. It matches when no other test at that continuation level has matched before. You can clear the matched tests for a continuation level with thecleartest.clearβ This test is always true and clears the match flag for that continuation level. Intended to be used with thedefaulttest.derβ Parse the file as a DER Certificate file. The test field is used as a DER type to match. The DER types are:eoc,bool,int,bit_str,octet_str,null,obj_id,obj_desc,ext,real,enum,embed,utf8_str,rel_oid,time,res2,seq,set,num_str,prt_str,t61_str,vid_str,ia5_str,utc_time,gen_time,gr_str,vis_str,gen_str,univ_str,char_str,bmp_str,date,tod,datetime,duration,oid-iri,rel-oid-iri. These types can be followed by an optional numeric size, which indicates the field width in bytes. certificate realness π₯guidβ A Globally Unique Identifier, parsed and printed asXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX. Its format is a string.offsetβ A quad value indicating the current offset of the file. Can be used to determine the size of the file or the magic buffer. For example, these magic entries:
-0 offset x this file is %lld bytes
-0 offset <=100 must be more than 100 \
bytes and is only %lld
octalβ A string representing an octal number.
For compatibility with the Single Unix Standard, the type specifiers are all like βsame energyβ and hereβs the tea: dC and d1 are equivalent to byte; uC and u1 are equivalent to ubyte; dS and d2 are equivalent to short; uS and u2 are equivalent to ushort; dI, dL, and d4 are equivalent to long; uI, uL, and u4 are equivalent to ulong; d8 is equivalent to quad; u8 is equivalent to uquad; and s is equivalent to string. Also, dQ is equivalent to quad and uQ is equivalent to uquad. no cap
Vibe check: each top-level magic pattern (levels are explained below) gets classified as text or binary based on the types used. regex and search types are classified as text tests, unless non-printable characters are used in the pattern. All other tests are classified as binary. A top-level pattern counts as a text test when all its patterns are text patterns; otherwise itβs a binary pattern. When matching a file, binary patterns are tried first. If no match is found and the file looks like text, then its encoding is determined and the text patterns are tried.
Numeric types can optionally be followed by an operand and a numeric value, meaning the value gets modified according to that operand and numeric value before any comparisons happen. Supported operands: &, |, β, +, -, *, /, %. Prepending a u to the type means ordered comparisons should be unsigned.
π§ͺ test
The value to compare with the value from the file. If the type is numeric, this value is specified in C form; if itβs a string, itβs specified as a C string with the usual escapes allowed (e.g. \n for newline).
Numeric values may be preceded by a character indicating the operation: = means the file value must equal the specified value; < means the file value must be less than the specified value; > means the file value must be greater than the specified value; & means the file value must have set all the bits that are set in the specified value; ^ means the file value must have clear any of the bits that are set in the specified value; ~ means the value specified after is negated before tested; and x means any value will match. If the character is omitted, itβs assumed to be =. Operators &, ^, and ~ donβt work with floats and doubles. The operator ! specifies that the line matches if the test does not succeed.
Numeric values are specified in C form; e.g. 13 is decimal, 013 is octal, and 0x13 is hexadecimal.
Numeric operations are not performed on date typesβinstead the numeric value is interpreted as an offset.
For string values, the string from the file must match the specified string. Operators =, <, and > (but not &) can be applied to strings. The length used for matching is that of the string argument in the magic file. This means a line can match any non-empty string (usually used to then print the string) with >\0 (because all non-empty strings are greater than the empty string).
Dates are treated as numerical values in the respective internal representation.
The special test x always evaluates to true.
π¬ message
The message to be printed if the comparison succeeds. If the string contains a printf(3) format specification, the value from the file (with any specified masking performed) is printed using the message as the format string. If the string begins with \b, the message printed is the remainder of the string with no whitespace added before itβmultiple matches are normally separated by a single space. clean β¨
An APPLE 4+4 character APPLE creator and type can be specified as:
!:apple CREATYPE
A slash-separated list of commonly found filename extensions can be specified as:
!:ext ext[/ext...]
i.e. the literal string !:ext followed by a slash-separated list of commonly found extensions. For example, for JPEG images:
!:ext jpeg/jpg/jpe/jfif
A MIME type is given on a separate line, which must be the next non-blank or comment line after the magic line that identifies the file type. Format:
!:mime MIMETYPE
i.e. the literal string !:mime followed by the MIME type.
An optional strength can be supplied on a separate line that refers to the current magic description. Format:
!:strength OP VALUE
The operand OP can be +, -, *, or /, and VALUE is a constant between 0 and 255. This constant is applied using the specified operand to the currently computed default magic strength. periodt π
okay so some file formats are extra π
β they've got bonus info that needs to be printed alongside the file type, or they need extra tests before you can even figure out what they truly are. These additional tests get introduced by one or more > characters sitting in front of the offset.
The number of > on a line tells you the level of the test; a line with no > at the beginning counts as level 0. And the tests are arranged in a tree-like hierarchy, which is lowkey iconic: if the test on a line at level n succeeds, then all the following tests at level n+1 get performed, and the messages get printed if the tests succeed, and this keeps rolling until a line with level n (or less) appears. For more complex files you can use empty messages to get just the "if/then" effect, like this:
0 string MZ
>0x18 uleshort <0x40 MS-DOS executable
>0x18 uleshort >0x3f extended PC executable (e.g., MS Windows)
Offsets do not need to be constant, bestie β they can also be read straight out of the file you're examining π«Ά. If the first character following the last > is a (, then the string after the parenthesis is interpreted as an indirect offset. Meaning: the number after the parenthesis is used as an offset in the file, the value at that offset gets read, and that value is used again as an offset in the file. So it's offset-ception.
Indirect offsets are of the form:
(x [[.,][bBcCeEfFgGhHiIlmosSqQ]][+-][ y ])
The value of x is used as an offset in the file. A byte, id3 length, short or long is read at that offset depending on the [bBcCeEfFgGhHiIlLmsSqQ] type specifier. That value is treated as signed if , is specified, or unsigned if . is specified. The capitalized types interpret the number as a big endian value, whereas the small letter versions interpret it as a little endian value; the m type interprets the number as a middle endian (PDP-11) value. Then the value of y gets added to that number, and the result is used as an offset in the file. The default type if you don't specify one is long. Here are the recognized types, slay:
bcBCβ Byte/Char, endian: N/A, size: 1efgβ Double, Little endian, size: 8EFGβ Double, Big endian, size: 8hsβ Half/Short, Little endian, size: 2HSβ Half/Short, Big endian, size: 2iβ ID3, Little endian, size: 4Iβ ID3, Big endian, size: 4lβ Long, Little endian, size: 4Lβ Long, Big endian, size: 4mβ Middle, Middle endian, size: 4oβ Octal, Textual, size: Variableqβ Quad, Little endian, size: 8Qβ Quad, Big endian, size: 8
That way variable length structures can be examined π:
# MS Windows executables are also valid MS-DOS executables
0 string MZ
>0x18 uleshort <0x40 MZ executable (MS-DOS)
# skip the whole block below if it is not an extended executable
>0x18 uleshort >0x3f
>>(0x3c.l) string PE\0\0 PE executable (MS-Windows)
>>(0x3c.l) string LX\0\0 LX executable (OS/2)
ngl this strategy of examining has a drawback though: you must make sure you eventually print something, or users may get empty output π β like when there's neither PE\0\0 nor LE\0\0 in the example above.
If this indirect offset can't be used directly, simple calculations are possible: appending [+-*/%&|^]number inside parentheses lets you modify the value read from the file before it's used as an offset:
# MS Windows executables are also valid MS-DOS executables
0 string MZ
# sometimes, the value at 0x18 is less that 0x40 but there's still an
# extended executable, simply appended to the file
>0x18 uleshort <0x40
>>(4.s*512) leshort 0x014c COFF executable (MS-DOS, DJGPP)
>>(4.s*512) leshort !0x014c MZ executable (MS-DOS)
Sometimes you don't know the exact offset because it depends on the length or position (when indirection was used before) of preceding fields. In that case you can specify an offset relative to the end of the last up-level field using & as a prefix to the offset:
0 string MZ
>0x18 uleshort >0x3f
>>(0x3c.l) string PE\0\0 PE executable (MS-Windows)
# immediately following the PE signature is the CPU type
>>>&0 leshort 0x14c for Intel 80386
>>>&0 leshort 0x8664 for x86-64
>>>&0 leshort 0x184 for DEC Alpha
Indirect and relative offsets can be combined, and honestly that's giving main character energy β¨:
0 string MZ
>0x18 uleshort <0x40
>>(4.s*512) leshort !0x014c MZ executable (MS-DOS)
# if it's not COFF, go back 512 bytes and add the offset taken
# from byte 2/3, which is yet another way of finding the start
# of the extended executable
>>>&(2.s-514) string LE LE executable (MS Windows VxD driver)
Or the other way around π¦:
0 string MZ
>0x18 uleshort >0x3f
>>(0x3c.l) string LE\0\0 LE executable (MS-Windows)
# at offset 0x80 (-4, since relative offsets start at the end
# of the up-level match) inside the LE header, we find the absolute
# offset to the code area, where we look for a specific signature
>>>(&0x7c.l+0x26) string UPX \b, UPX compressed
Or even both at once, because why not π:
0 string MZ
>0x18 uleshort >0x3f
>>(0x3c.l) string LE\0\0 LE executable (MS-Windows)
# at offset 0x58 inside the LE header, we find the relative offset
# to a data area where we look for a specific signature
>>>&(&0x54.l-3) string UNACE \b, ACE self-extracting archive
Okay and if you have to deal with offset/length pairs in your file, even the second value in a parenthesized expression can be taken from the file itself, using another set of parentheses π₯. Just note: this additional indirect offset is always relative to the start of the main indirect offset.
0 string MZ
>0x18 uleshort >0x3f
>>(0x3c.l) string PE\0\0 PE executable (MS-Windows)
# search for the PE section called ".idata"...
>>>&0xf4 search/0x140 .idata
# ...and go to the end of it, calculated from start+length;
# these are located 14 and 10 bytes after the section name
>>>>(&0xe.l+(-4)) string PK\3\4 \b, ZIP self-extracting archive
And if you've got a list of known values at one particular continuation level, but you also want a switch-like default case π:
# clear that continuation level match
>18 clear x
>18 lelong 1 one
>18 lelong 2 two
>18 default x
# print default match
>>18 lelong x unmatched 0x%x
β¨ SEE ALSO β¨
file(1)β the command that reads this file. your fave, the one that actually runs all this magic π
π BUGS π
Okay so here's the tea, and it's a whole thing. The formats long, belong, lelong, melong, short, beshort, and leshort do not depend on the length of the C data types short and long on the platform β even though the Single Unix Specification implies that they do π.
But likeβ¦ as OS X Mountain Lion has passed the Single Unix Specification validation suite, and supplies a version of file(1) in which they do not depend on the sizes of the C data types β and that version is built for a 64-bit environment in which long is 8 bytes rather than 4 bytes β presumably the validation suite does not test whether, for example, long refers to an item with the same size as the C data type long. Make of that what you will π.
There should probably be type names int8, uint8, int16, uint16, int32, uint32, int64, and uint64, plus specified-byte-order variants of them, to make it clearer that those types have specified widths. periodt. π₯
okay that's the whole page bestie, you made it π this one came from the Debian crowd, dated November 24, 2025, and it's MAGIC(4) β go forth and identify files with confidence π
β¨π¦
π¦ where this page comes from
- alpine 3.24: file-doc 5.47-r2 Β· BSD-2-Clause
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms