通过 os 包创建相对符号 link

Creating a relative symbolic link through the os package

我想使用 os 包在 go 中创建一个相对符号 link。

os 已经 contains the function: os.SymLink(oldname, newname string),但它无法创建相对符号 links。

例如,如果我 运行 以下内容:

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)
}

它在我的文件系统中创建了以下内容:

$ 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

如何使用 golang 来创建如下所示的相对符号link:

$ 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

我想要类似于上面 symrelative 的内容。

我必须求助于 os/exec:

cmd := exec.Command("ln", "-s", "symtarget.txt", "symlink")
cmd.Dir = "/tmp/rolfl/symexample"
cmd.CombinedOutput()

调用os.Symlink时不要包含symtarget.txt的绝对路径;仅在写入文件时使用它:

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)
}