2

I am trying to link files in a while loop for my script but just the simple linking code itself creates a broken link.

The directory structure is this:

main/working/script.sh
main/working/dir
main/shared/default/some_files

My script has this code:

ln -s ../shared/default/* dir

This creates broken link. I can make the link not broken if I go inside the directory of main/working/dir and use ln -s ../../shared/default/* .

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
Gibs
  • 774
  • 9
  • 26

1 Answers1

1

That is because you link to a relative path; Inside your script go to main/working/:

cd main/working/
ln -s ../shared/default/* dir

either use the absolute path:

ln -s /absolute/path/to/shared/default/* dir

you might even deduce the path where your script is located and use that path:

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
ln -s $DIR/../../shared/default/* dir

edit: bash cannot expand the * if you are not at the right directory, so you can work around that to temporarily change directories:

# go to dir to make correct relative links
cd dir
ln -s $DIR/../../shared/default/* ./
cd ..
Community
  • 1
  • 1
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
  • is there another way on linking it without using the absolute path? – Gibs Jul 01 '15 at 08:15
  • I gave you three possibilities; the first is relative, second absolute, third is a mix of both: relative to the place where your script is located... – Chris Maes Jul 01 '15 at 08:17
  • The first option you gave was the code I used and it gives broken links. The third option though is too long. – Gibs Jul 01 '15 at 08:18
  • your link is broken because you are not located in the correct directory; that's why you need to go to your working directory – Chris Maes Jul 01 '15 at 08:20
  • remark the line just before the one you used: `cd main/working` (note that you could use an absolute directory too here: `cd /path/to/main/working` – Chris Maes Jul 01 '15 at 08:21
  • My script.sh now contains this `cd main/working` `ln -s ../shared/default/* dir` and it says `No such file or directory` – Gibs Jul 01 '15 at 08:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/82056/discussion-between-chris-maes-and-gibs). – Chris Maes Jul 01 '15 at 08:27