How to differentiate between a file without an extension and a folder without using `cd`?

What is the difference between a file without an extension and a folder? What I mean exactly is that when I create a file in the terminal, for example:

touch somefile

then delete that file and create a directory with the same name:

mkdir somefile

they look the same in ls. How to differentiate between them without using cd somefile?

Also, I don't know how files without extensions work in Linux. I couldn't find an article on the internet, so I wish you can help me with it.


Solution 1:

The simplest way is to use the file command, which is generally used to determine a file's type (see man file). So, if you run:

file somefile

and the output is:

somefile: directory

then somefile is obviously a directory.

If somefile is not a directory, then you'll get an output depending on the file's type. For example, if somefile was a PNG image, you would get information about it similar to the following:

somefile: PNG image data, 730 x 518, 8-bit/color RGBA, non-interlaced

Files on Linux do not necessarily have an extension. Quoting from Byte Commander's answer in the question Do file-extensions have any purpose (for the operating system)? :

Usually Linux does not rely on file names (and file extensions i.e. the part of the file name after the normally last period) and instead determines the file type by examining the first few bytes of its content and comparing that to a list of known magic numbers.

Solution 2:

You can run

ls -l

Directories will have d in the permissions, like

drwxr-xr-x

Also in Ubuntu directories are blue.

Solution 3:

Let's test this by creating a file (test) and a directory (testfile):

me:~$ touch test
me:~$ mkdir testfile

If you are using a color terminal, you can see the difference using plain old ls. Directories are a different color:

me:~$ ls
test  testfile   # Oops, we said color!

enter image description here

If you are using a monochrome terminal, use the -l flag. You can see the difference in the first column of output:

me:~$ ls -l
total 4
-rw-rw-r-- 1 me me    0 Aug 14 11:49 test
drwxrwxr-x 2 me me 4096 Aug 14 11:49 testfile