253

Below is my code for creating a symlink of a directory:

sudo ln -s /usr/local/nginx/conf/ /etc/nginx

I already created the directory /etc/nginx. I just want the contents of the source directory (/usr/local/nginx/conf/) to be in the contents of the target directory (/etc/nginx). But when I execute the code, /etc/nginx contains a directory called conf, instead of the contents of conf. That directory contains the contents I want, but in the wrong location.

Why did it put a directory in the target folder, instead of just putting the contents of the directory in the target folder?

nbro
  • 15,395
  • 32
  • 113
  • 196
  • You can also use Files (default file browser). Right click on the folder you want to link > "Make Link" option. It will create linked folder which you can move and rename as you need. – John Linhart Jun 05 '14 at 12:58
  • 4
    Use linux `bind mount` feature. [example](http://backdrift.org/how-to-use-bind-mounts-in-linux) – gkiko Dec 05 '15 at 19:09

3 Answers3

266

This is the behavior of ln if the second arg is a directory. It places a link to the first arg inside it. If you want /etc/nginx to be the symlink, you should remove that directory first and run that same command.

tshepang
  • 12,111
  • 21
  • 91
  • 136
FatalError
  • 52,695
  • 14
  • 99
  • 116
31

That's what ln is documented to do when the target already exists and is a directory. If you want /etc/nginx to be a symlink rather than contain a symlink, you had better not create it as a directory first!

Celada
  • 21,627
  • 4
  • 64
  • 78
  • 52
    Your answer only makes sense in the context of the reader already knowing the answer. It is useless to anyone who would ask the question – Ricardo Saporta May 01 '13 at 05:31
  • 1
    Can I actually create a symlink to a root of a mounted USB device (thus I cannot erase this folder first)? – Grigory Kornilov Mar 24 '15 at 19:02
  • 1
    @GrigoryKornilov you can create a symlink *to* anything you want, including something that doesn't exist. This question was rather about the place where the symlink is created (not where it points to). A particular pathname in the filesystem is either a regular file or it is a directory or it is a symlink (or it is a socket or pipe or device). It cannot *be* more than one of those things at the same time (i.e. you cannot have more than one distinct file with the exact same name). – Celada Mar 25 '15 at 00:23
11

In script is useful something like this:

if [ ! -d /etc/nginx ]; then ln -s /usr/local/nginx/conf/ /etc/nginx > /dev/null 2>&1; fi

it prevents before re-create "bad" looped symlink after re-run script

kayn
  • 673
  • 5
  • 14
  • 1
    Excellent! This is the exact solution. no need to create the directory if it already existing. It's a real good tweak to hard link and sink it in the blackhole(/dev/null) – Arun Panneerselvam Apr 01 '20 at 15:13