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()
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With