readlink.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini readlink implementation for busybox
  4. *
  5. * Copyright (C) 2000,2001 Matt Kraai <kraai@alumni.carnegiemellon.edu>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. //usage:#define readlink_trivial_usage
  10. //usage: IF_FEATURE_READLINK_FOLLOW("[-fnv] ") "FILE"
  11. //usage:#define readlink_full_usage "\n\n"
  12. //usage: "Display the value of a symlink"
  13. //usage: IF_FEATURE_READLINK_FOLLOW( "\n"
  14. //usage: "\n -f Canonicalize by following all symlinks"
  15. //usage: "\n -n Don't add newline"
  16. //usage: "\n -v Verbose"
  17. //usage: )
  18. #include "libbb.h"
  19. /*
  20. * # readlink --version
  21. * readlink (GNU coreutils) 6.10
  22. * # readlink --help
  23. * -f, --canonicalize
  24. * canonicalize by following every symlink in
  25. * every component of the given name recursively;
  26. * all but the last component must exist
  27. * -e, --canonicalize-existing
  28. * canonicalize by following every symlink in
  29. * every component of the given name recursively,
  30. * all components must exist
  31. * -m, --canonicalize-missing
  32. * canonicalize by following every symlink in
  33. * every component of the given name recursively,
  34. * without requirements on components existence
  35. * -n, --no-newline do not output the trailing newline
  36. * -q, --quiet, -s, --silent suppress most error messages
  37. * -v, --verbose report error messages
  38. *
  39. * bbox supports: -f -n -v (fully), -q -s (accepts but ignores)
  40. */
  41. int readlink_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  42. int readlink_main(int argc UNUSED_PARAM, char **argv)
  43. {
  44. char *buf;
  45. char *fname;
  46. IF_FEATURE_READLINK_FOLLOW(
  47. unsigned opt;
  48. /* We need exactly one non-option argument. */
  49. opt_complementary = "=1";
  50. opt = getopt32(argv, "fnvsq");
  51. fname = argv[optind];
  52. )
  53. IF_NOT_FEATURE_READLINK_FOLLOW(
  54. const unsigned opt = 0;
  55. if (argc != 2) bb_show_usage();
  56. fname = argv[1];
  57. )
  58. /* compat: coreutils readlink reports errors silently via exit code */
  59. if (!(opt & 4)) /* not -v */
  60. logmode = LOGMODE_NONE;
  61. if (opt & 1) { /* -f */
  62. buf = xmalloc_realpath(fname);
  63. } else {
  64. buf = xmalloc_readlink_or_warn(fname);
  65. }
  66. if (!buf)
  67. return EXIT_FAILURE;
  68. printf((opt & 2) ? "%s" : "%s\n", buf);
  69. if (ENABLE_FEATURE_CLEAN_UP)
  70. free(buf);
  71. fflush_stdout_and_exit(EXIT_SUCCESS);
  72. }