3

I want to create a simple symlink to a file.

It works perfectly if I run the command from inside the directory where I want the symlink to be created:

/path/to/link $ ln -s /path/to/file .

But if I'm in any other directory, it creates a broken link every time:

/any/other/path $ ln -s /path/to/file /path/to/link

Does ln -s require to you to be in a certain directory, or am I missing something? Running Ubuntu 10.04.

Update: Sorry for the confusion about whether the paths were relative or absolute. They were relative, and as several mentioned in their answers this was the source of my problem. Thanks!

evanrmurphy
  • 133
  • 1
  • 5

5 Answers5

5

If you are not in the same directory as the target you must make sure you use the absolute path.

ln -s foo/bar baz/quux # fails

ln -s ~/foo/bar baz/quux # succeeds
sverre
  • 176
3

I tend to use

ln -s $(pwd)/local_file /path/to/link

when I need to link a local file.

clemens
  • 131
1

This is always unintutive to me. I get in the habit of doing:

ln -s $(readlink -f /path/to/file) /path/to/link

which should work but at the cost of making it non-relative in the actual on-disk link.

0

No, there is no such requirement:

aix@aix:/tmp$ cd /tmp
aix@aix:/tmp$ mkdir test_path
aix@aix:/tmp$ echo test > test_path/file.txt
aix@aix:/tmp$ ln -s /tmp/test_path/file.txt /tmp/test_path/link.txt
aix@aix:/tmp$ cat /tmp/test_path/link.txt
test

Make sure you have't mistyped any of the paths, and that you're using absolute paths everywhere (as your example indicates).

NPE
  • 1,239
0

It's not really about which directory you're in, in itself. It's about what symlink you make: symlinks are just files that contain a path that points to a file. You can make symlinks that contain paths that start with the / character, or symlinks that don't start with that character. You can create symlinks that contain .. path components, and symlinks that don't. When programs resolve symlinks to find the target file, they interpret the path as being relative to the directory that contains the symlink. So you just need to make sure the symlink has the path that you want.

Here's one way that's similar to Matthew Flaschen's answer, but here making a relative symlink:

/tmp$ mkdir -p spam/eggs/ham
/tmp$ mkdir foo
/tmp$ python -c "import os, sys; print os.path.relpath(sys.argv[1], os.path.abspath(sys.argv[2])), sys.argv[2]" $(readlink -e foo) spam/eggs/ham  | xargs ln -s 
/tmp$ ls -l spam/eggs/ham/foo
lrwxrwxrwx 1 user user 12 2012-02-05 15:12 spam/eggs/ham/foo -> ../../../foo

No doubt that could be done in pure Bourne / bash shell too, but it's easy to write (and read) this correctly in python.

Croad Langshan
  • 878
  • 9
  • 22