1 /* ln.c - Create filesystem links
3 * Copyright 2012 Andre Renaud <andre@bluewatersys.com>
5 * See http://opengroup.org/onlinepubs/9699919799/utilities/ln.html
7 USE_LN(NEWTOY(ln, "<1vnfs", TOYFLAG_BIN))
13 usage: ln [-sfnv] [FROM...] TO
15 Create a link between FROM and TO.
16 With only one argument, create link in current directory.
18 -s Create a symbolic link
19 -f Force the creation of the link, even if TO already exists
20 -n Symlink at destination treated as file
29 char *dest = toys.optargs[--toys.optc], *new;
33 // With one argument, create link in current directory.
39 // Is destination a directory?
40 if (((toys.optflags&FLAG_n) ? lstat : stat)(dest, &buf)
41 || !S_ISDIR(buf.st_mode))
43 if (toys.optc>1) error_exit("'%s' not a directory", dest);
47 for (i=0; i<toys.optc; i++) {
49 char *oldnew, *try = toys.optargs[i];
51 if (S_ISDIR(buf.st_mode)) new = xmprintf("%s/%s", dest, basename(try));
54 // Force needs to unlink the existing target (if any). Do that by creating
55 // a temp version and renaming it over the old one, so we can retain the
56 // old file in cases we can't replace it (such as hardlink between mounts).
58 if (toys.optflags & FLAG_f) {
59 new = xmprintf("%s_XXXXXX", new);
63 if (unlink(new)) perror_msg("unlink '%s'", new);
67 rc = (toys.optflags & FLAG_s) ? symlink(try, new) : link(try, new);
68 if (toys.optflags & FLAG_f) {
72 rc = rename(new, oldnew);
74 if (rc && unlink(new)) perror_msg("unlink '%s'", new);
81 perror_msg("cannot create %s link from '%s' to '%s'",
82 (toys.optflags & FLAG_s) ? "symbolic" : "hard", try, new);
84 if (toys.optflags & FLAG_v) fprintf(stderr, "'%s' -> '%s'\n", new, try);
86 if (new != dest) free(new);