Creating a relative symbolic link through the os package
Asked Answered
S

1

15

I would like to create a relative symbolic link in go using the os package.

os already contains the function: os.SymLink(oldname, newname string), but it cannot create relative symlinks.

For example, if I run the following:

package main 

import (
    "io/ioutil"
    "os"
    "path/filepath"
)

func main() {
    path := "/tmp/rolfl/symexample"
    target := filepath.Join(path, "symtarget.txt")
    os.MkdirAll(path, 0755)
    ioutil.WriteFile(target, []byte("Hello\n"), 0644)
    symlink := filepath.Join(path, "symlink")
    os.Symlink(target, symlink)
}

it creates the following in my filesystem:

$ ls -la /tmp/rolfl/symexample
total 12
drwxr-xr-x 2 rolf rolf 4096 Feb 21 15:21 .
drwxr-xr-x 3 rolf rolf 4096 Feb 21 15:21 ..
lrwxrwxrwx 1 rolf rolf   35 Feb 21 15:21 symlink -> /tmp/rolfl/symexample/symtarget.txt
-rw-r--r-- 1 rolf rolf    6 Feb 21 15:21 symtarget.txt

How can I use golang to create the relative symlink that looks like:

$ ln -s symtarget.txt symrelative
$ ls -la
total 12
drwxr-xr-x 2 rolf rolf 4096 Feb 21 15:23 .
drwxr-xr-x 3 rolf rolf 4096 Feb 21 15:21 ..
lrwxrwxrwx 1 rolf rolf   35 Feb 21 15:21 symlink -> /tmp/rolfl/symexample/symtarget.txt
lrwxrwxrwx 1 rolf rolf   13 Feb 21 15:23 symrelative -> symtarget.txt
-rw-r--r-- 1 rolf rolf    6 Feb 21 15:21 symtarget.txt

I want something that's like the symrelative above.

Do I have to resort to os/exec:

cmd := exec.Command("ln", "-s", "symtarget.txt", "symlink")
cmd.Dir = "/tmp/rolfl/symexample"
cmd.CombinedOutput()
Silverweed answered 21/2, 2016 at 20:25 Comment(0)
S
19

Don't include the absolute path to symtarget.txt when calling os.Symlink; only use it when writing to the file:

package main 

import (
    "io/ioutil"
    "os"
    "path/filepath"
)

func main() {
    path := "/tmp/rolfl/symexample"
    target := "symtarget.txt"
    os.MkdirAll(path, 0755)
    ioutil.WriteFile(filepath.Join(path, "symtarget.txt"), []byte("Hello\n"), 0644)
    symlink := filepath.Join(path, "symlink")
    os.Symlink(target, symlink)
}
Snippy answered 21/2, 2016 at 20:50 Comment(4)
How come this is an answer?? It doesn't create relative symlink at all. Just to reming: relative symlink could look like: a.txt -> ../../something/a.txtRoscoe
@Roscoe os.Symlink("../../something/a.txt", "/tmp/foo/bar/a.txt")Wed
@Wed "/tmp/foo/bar/a.txt" is an absolute path.Roscoe
@Roscoe Yes, this snippet will create symlink a.txt in the /tmp/foo/bar/ directory that points to the ../../something/a.txt <br> ~$ ls -og /tmp/foo/bar/ total 0 lrwxrwxrwx 1 21 Mär 25 19:15 a.txt -> ../../something/a.txtWed

© 2022 - 2024 — McMap. All rights reserved.