ยง2023-11-18

The readlink command resolves paths for canonical file names or symbolic links.

The readlink command is used to display the value of a symbolic link or canonicalize the path of a file or directory. When we talk about "canonical file names" in the context of readlink, we are usually referring to resolving symbolic links or providing the absolute, standardized path of a file.

Here's a brief explanation of these terms:

Symbolic link (symlink): A symbolic link is a special type of file that acts as a reference to another file or directory. It contains a path that points to the location of the target file or directory. When you use readlink on a symbolic link, it displays the path to which the link points.

Canonical path or canonical file name: The canonical path is the absolute, standardized, and fully resolved path of a file or directory, without any symbolic links or relative components. It represents the real, physical location of the file or directory on the file system.

for example:

$ touch hello.txt
$ ln -sf hello.txt file1
$ ln -sf file1 file2
$ ls -l
total 0
lrwxrwxrwx 1 alexlai alexlai 9 Nov 18 14:48 file1 -> hello.txt
lrwxrwxrwx 1 alexlai alexlai 5 Nov 18 14:48 file2 -> file1
-rw-r--r-- 1 alexlai alexlai 0 Nov 18 14:47 hello.txt
hello.txt
$ readlink file2
file1
$ rm hello.txt 
$ readlink file1
hello.txt
$ readlink file2
file1
$ ls -l
total 0
lrwxrwxrwx 1 alexlai alexlai 9 Nov 18 14:48 file1 -> hello.txt
lrwxrwxrwx 1 alexlai alexlai 5 Nov 18 14:48 file2 -> file1

$ readlink -f file1
/home/alexlai/build/test/hello.txt
$ readlink -e file1
$ readlink -m file1
/home/alexlai/build/test/hello.txt
$ readlink -m file2
/home/alexlai/build/test/hello.txt
$ readlink -e file1
$ readlink -f file1
/home/alexlai/build/test/hello.txt

#!/usr/bin/env bash
SCRIPTDIR=$(dirname "$(readlink -f "$0")")
echo "absolute path of the script $0 is $SCRIPTDIR"