github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/readlink/readlink.go (about)

     1  // Copyright 2013-2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // readlink display value of symbolic link file.
     6  //
     7  // Synopsis:
     8  //     readlink [OPTIONS] FILE
     9  //
    10  // Options:
    11  //     -f: follow
    12  //     -n: nonewline
    13  //     -v: verbose
    14  package main
    15  
    16  import (
    17  	"flag"
    18  	"fmt"
    19  	"os"
    20  	"path/filepath"
    21  )
    22  
    23  const cmd = "readlink [-fnv] FILE"
    24  
    25  var (
    26  	delimiter = "\n"
    27  	follow    = flag.Bool("f", false, "follow recursively")
    28  	nonewline = flag.Bool("n", false, "do not output trailing newline")
    29  	verbose   = flag.Bool("v", false, "report error messages")
    30  )
    31  
    32  func init() {
    33  	defUsage := flag.Usage
    34  	flag.Usage = func() {
    35  		os.Args[0] = cmd
    36  		defUsage()
    37  	}
    38  	flag.Parse()
    39  }
    40  
    41  func readLink(file string) error {
    42  	path, err := os.Readlink(file)
    43  	if err != nil {
    44  		return err
    45  	}
    46  
    47  	if *follow {
    48  		path, err = filepath.EvalSymlinks(file)
    49  	}
    50  
    51  	if *nonewline {
    52  		delimiter = ""
    53  	}
    54  
    55  	fmt.Printf("%s%s", path, delimiter)
    56  	return err
    57  }
    58  
    59  func main() {
    60  	var exitStatus int
    61  
    62  	for _, file := range flag.Args() {
    63  		if err := readLink(file); err != nil {
    64  			if *verbose {
    65  				fmt.Fprintf(os.Stderr, "%v\n", err)
    66  			}
    67  			exitStatus = 1
    68  		}
    69  	}
    70  
    71  	os.Exit(exitStatus)
    72  }