How to Work with Symlinks and Hard Links in Go

Create symbolic links with os.Symlink and hard links with os.Link in Go, using os.Lstat to inspect symlinks without following them.

Use os.Symlink to create symbolic links and os.Lstat to inspect them without following the link target. Hard links are created with os.Link and share the same inode as the original file.

package main

import (
	"fmt"
	"os"
)

func main() {
	// Create a symbolic link
	err := os.Symlink("original.txt", "link.txt")
	if err != nil {
		fmt.Println("Symlink error:", err)
		return
	}

	// Inspect the symlink without following it
	info, err := os.Lstat("link.txt")
	if err != nil {
		fmt.Println("Lstat error:", err)
		return
	}
	fmt.Println("IsSymlink:", info.Mode()&os.ModeSymlink != 0)

	// Create a hard link
	err = os.Link("original.txt", "hardlink.txt")
	if err != nil {
		fmt.Println("Hard link error:", err)
		return
	}
}