One of the interesting interview question or concept for a directory or file on linux bash shell is “what are the default link count of a file/dir when its created.”
Let us have a look at its answer and try to understand it.
Q1. How many link count does a directory or file has by default ?
A1. By default, every new file created has one link count i.e. its linked to itself.
And every new directory has 2 link counts: 1 link is mapped for the directory itself, and another link is created inside directory with name “.” which points to the present working directory.
Q2. How to view number of link counts ?
We can view the link counts in “ls -l” command output.
The second column data used to show the link count of a particular file/directory.
[root@nglinux testdir]# ls -ltr total 16 -rw-r--r--. 1 root root 42 Feb 22 11:44 file1.txt.gz -rw-r--r--. 1 root root 145 Feb 22 11:45 file1.tar.gz -rw-r--r--. 1 root root 81 May 8 14:35 testfile drwxr-xr-x. 2 root root 4096 May 11 12:57 sample
Note:- Always remember the link count is the hard link count of the particular file/directory.
Let us look at an example to understand this.
a. Create new file and directory.
ngelinux:testdir saket$ touch file1 ngelinux:testdir saket$ mkdir dir1 ### 1 link is for the directory or file itself. ### In case of directory: Another link is of "." present in current directory. ### Checkout the links. 01HW860266:testdir saket$ ls -l total 0 drwxr-xr-x 2 saket staff 68 May 2 11:35 dir1 -rw-r--r-- 1 saket staff 0 May 2 11:35 file1 ngelinux:testdir saket$
New file contains one link. And a new directory contains two links.
b. Each directory contains the link count of 2(default)+N where N is the number of subdirectories inside the directory.
Lets look at this via an example.
ngelinux:testdir saket$ mkdir dir1/sampledir1 ngelinux:testdir saket$ ls -l total 0 drwxr-xr-x 3 saket staff 102 May 2 11:39 dir1 -rw-r--r-- 1 saket staff 0 May 2 11:35 file1
We can see above a link count is increased because the newly created sub-directory has a link “..” which maps to this parent directory and so on with increasing number of directories.