|
|
Linux Secrets: How to Create a Link with lnUse the Linux Command ln to Define Links to a File
The Linux command ln allows a user to create multiple names for the same file.
As any Linux programmer goes about their daily business they'll create new programs and give them nice sensible names. However, for the users it may be a laborious job having to type out a long file name all of the time - they wants something short and snappy - a nice little tla (three letter abreviation) for example. So, the question is - how can the two needs be reconciled? The answer is to use Linux Links. An Example Script - the Disk Usage CheckerThe starting point is a simple, yet useful, script - this will report any disk with more that 90% usage, and can be created very easily: $ cd ~/bin
$ cat > check_disk_usage
df|
grep -v "Mounted on" |
awk '{
gsub("%","")
if ($5 > 90) {print $1" - Alarm"}
}'
<CTRL-D>
$ chmod +x check_disk_usage
For the Linux programmer this has been named perfectly as check_disk_usage, but the user may want something simpler and easy to type - for example cdu; therefore, the next step is to create a link Creating a Linux LinkThe link is created by using the command: $ ln check_disk_usage cdu
If the directory is examined then two new files will be shown: $ ls -1 c*
cdu
check_disk_usage
The files will have the same size and creation date/time: $ ls -l c*
-rwxrwxrwx 2 bainm bainm 84 2008-12-05 15:19 cdu
-rwxrwxrwx 2 bainm bainm 84 2008-12-05 15:19 check_disk_usage
And even the inodes are the same: $ ls -i1 c*
1002029 cdu
1002029 check_disk_usage
In this case a hard link has been created and, as far as the system is concerned, they are the same file; however, there is a problem with using a hard link - it doesn't always work when the file and the link are in different directories (especially if those directories are on different disks). The solution is to use a symbolic link. Symbolic LinksRather than being a direct link (as with the hard link) the symbolic link simply holds the path to the target file; it's created by using the -s option with ln: $ rm cdu
$ ln -s check_disk_usage cdu
This time the inodes are different: 1002025 cdu
1002029 check_disk_usage
And the link is shown as such in the directory listing: lrwxrwxrwx 1 bainm bainm 16 2008-12-05 15:48 cdu -> check_disk_usage
-rwxrwxrwx 1 bainm bainm 84 2008-12-05 15:19 check_disk_usage
SummaryThe Linux link enables the user to reference the same file with more that one name - and to that they use the ln command; the ln command can be used in two ways:
Although the hard link is the default, it is always better to use the symbolic links so that it can be placed anywhere in the system.
The copyright of the article Linux Secrets: How to Create a Link with ln in Linux Programming is owned by Mark Alexander Bain. Permission to republish Linux Secrets: How to Create a Link with ln in print or online must be granted by the author in writing.
|
|
|
|
|
|
|
|