Identify a file's type in Ubuntu

In this article, we cover how to identify a file’s type in Ubuntu. In Ubuntu we have – regular files, directories, symbolic links, device files (or, special files) and executables. Generally, we tend to identify a file’s type by the extension a file ends with. But, that is not a reliable method. Reason: One can easily change the extension of a file with rename option. But, its just the extension we have changed and not its file type. So, the underlying structure of the file stays the same.

Identify a file’s type in Ubuntu

The command-line utility which can help us identify a file’s type is file. Use the following syntax –

file <file-name>

For instance, open a terminal and create a file with nano command –

nano test-file

Enter today’s date in the test-file and save-exit.

Nov 28, 2022

You would notice that, we haven’t provided an extension to the file. In Ubuntu, we can create and use files without an extension. And, that is the reason why at the beginning of the article we mentioned that identifying a file type with the extension it ends with is not a reliable method.

At this stage, we assume that you don’t know the file type of test-file. So, use the following command –

file test-file

It would return with –

test-file: ASCII text

Now, change extension of a file and check whether the file type changes with the change in extension? And, compare both the outcomes. You would see that the outcome is still the same on both the occasions. The file type stays the same irrespective of the changes we do to extensions.

Apart from that, notice the colon (:) in the output above. Its a separator. We can change it with the help of -F option. Use following syntax –

file -F separator <file-name>

For instance, if we intend to put # as the separator then put it in quotes as –

file -F "#" test-file

This time around it returns with –

test-file# ASCII text

If you don’t want the filename to show in output then use -b option –

file -b test-file

It returns with –

ASCII text

Lastly, to get output in mime type strings format –

file -i test-file

The output would be –

test-file: text/plain; charset=us-ascii

In conclusion, we have covered how to identify a file’s type in Ubuntu.

Similar Posts