which.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
  4. * Copyright (C) 2006 Gabriel Somlo <somlo at cmu.edu>
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. */
  8. //config:config WHICH
  9. //config: bool "which"
  10. //config: default y
  11. //config: help
  12. //config: which is used to find programs in your PATH and
  13. //config: print out their pathnames.
  14. //applet:IF_WHICH(APPLET(which, BB_DIR_USR_BIN, BB_SUID_DROP))
  15. //kbuild:lib-$(CONFIG_WHICH) += which.o
  16. //usage:#define which_trivial_usage
  17. //usage: "[COMMAND]..."
  18. //usage:#define which_full_usage "\n\n"
  19. //usage: "Locate a COMMAND"
  20. //usage:
  21. //usage:#define which_example_usage
  22. //usage: "$ which login\n"
  23. //usage: "/bin/login\n"
  24. #include "libbb.h"
  25. int which_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  26. int which_main(int argc UNUSED_PARAM, char **argv)
  27. {
  28. const char *env_path;
  29. int status = 0;
  30. env_path = getenv("PATH");
  31. if (!env_path)
  32. env_path = bb_default_root_path;
  33. opt_complementary = "-1"; /* at least one argument */
  34. getopt32(argv, "a");
  35. argv += optind;
  36. do {
  37. int missing = 1;
  38. /* If file contains a slash don't use PATH */
  39. if (strchr(*argv, '/')) {
  40. if (file_is_executable(*argv)) {
  41. missing = 0;
  42. puts(*argv);
  43. }
  44. } else {
  45. char *path;
  46. char *tmp;
  47. char *p;
  48. path = tmp = xstrdup(env_path);
  49. while ((p = find_executable(*argv, &tmp)) != NULL) {
  50. missing = 0;
  51. puts(p);
  52. free(p);
  53. if (!option_mask32) /* -a not set */
  54. break;
  55. }
  56. free(path);
  57. }
  58. status |= missing;
  59. } while (*++argv);
  60. return status;
  61. }