30
> cd /tmp
> ln -s foo
> ls -alhF /tmp
lrwxrwxrwx 1 user user    3 Jul 29 14:00 foo -> foo

Is this a bug in ln or is there a use case for symlinking a file to itself?

This is with coreutils 8.21-1ubuntu5.1.

0

2 Answers 2

47

It's not a bug. The use case is for when you want to link a file to the same basename but in a different directory:

cd /tmp
ln -s /etc/passwd
ls -l passwd
lrwxrwxrwx 1 xxx xxx 11 Jul 29 09:10 passwd -> /etc/passwd

It's true that when you do this with a filename that is in the same directory it creates a link to itself which does not do a whole lot of good!

This works regardless of whether you use symlinks or hard links.

3
  • 17
    Another way to put it: ln -s /path/to/file is short for ln -s /path/to/file .. Like ls is short for ls .. Commented Jul 29, 2015 at 15:10
  • 3
    @StéphaneChazelas yes, and you save two whole keystrokes! :-)
    – Celada
    Commented Jul 29, 2015 at 15:12
  • 4
    Note that that behaviour is not specified by POSIX but seems to be fairly common (GNU, busybox, FreeBSD, Solaris, Ultrix at least, and was already like that (though -s wasn't supported of course) in the first version of Unix in the early 70s). Commented Jul 29, 2015 at 15:27
9

The easiest way to find out of course, is to try it and see. When no 2nd argument is given, ln will create a link in the current directory with the same name as the original:

$ ln -s /etc
$ ls -l
lrwxrwxrwx 1 terdon terdon         4 Jul 29 16:09 etc -> /etc

This is also explained in man ln:

In the 2nd form, create a link to TARGET in the current directory.

The "2nd form" refers to:

ln [OPTION]... TARGET (2nd form)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .