blob: 5ab67194db37924cd642dd448ed1773e0dcb2029 [file] [log] [blame]
Erik Andersen330fd2b2000-05-19 05:35:19 +00001/* vi: set sw=4 ts=4: */
2/*
3 * Which implementation for busybox
4 *
Eric Andersenc7bda1c2004-03-15 08:29:22 +00005 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
Denis Vlasenkof6f43df2006-10-11 22:16:56 +00006 * Copyright (C) 2006 Gabriel Somlo <somlo at cmu.edu>
Erik Andersen330fd2b2000-05-19 05:35:19 +00007 *
Bernhard Reutner-Fischer7fee0c42006-09-13 16:39:19 +00008 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
Erik Andersen330fd2b2000-05-19 05:35:19 +00009 *
Glenn L McGrathe84152e2004-03-01 08:32:49 +000010 * Based on which from debianutils
Erik Andersen330fd2b2000-05-19 05:35:19 +000011 */
12
Denis Vlasenkob6adbf12007-05-26 19:00:18 +000013#include "libbb.h"
Bernhard Reutner-Fischer66e3a222006-06-14 16:17:50 +000014
Denis Vlasenko9b49a5e2007-10-11 10:05:36 +000015int which_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
Rob Landleydfba7412006-03-06 20:47:33 +000016int which_main(int argc, char **argv)
Erik Andersen330fd2b2000-05-19 05:35:19 +000017{
Denis Vlasenkof6f43df2006-10-11 22:16:56 +000018 int status = EXIT_SUCCESS;
19 char *p;
Erik Andersen330fd2b2000-05-19 05:35:19 +000020
Denis Vlasenko01c27fc2006-10-05 21:10:53 +000021 if (argc <= 1 || argv[1][0] == '-') {
Manuel Novoa III cad53642003-03-19 09:13:01 +000022 bb_show_usage();
Glenn L McGrathe84152e2004-03-01 08:32:49 +000023 }
Erik Andersen330fd2b2000-05-19 05:35:19 +000024
Denis Vlasenko6446c2d2007-11-25 04:54:13 +000025 /* This matches what is seen on e.g. ubuntu
26 * "which" there is a shell script */
Denis Vlasenko9d938732007-01-28 15:31:19 +000027 if (!getenv("PATH")) {
Denis Vlasenkof5f75c52007-06-12 22:35:19 +000028 putenv((char*)bb_PATH_root_path);
Denis Vlasenko9d938732007-01-28 15:31:19 +000029 }
30
Denis Vlasenkof6f43df2006-10-11 22:16:56 +000031 while (--argc > 0) {
Paul Foxdb485cf2005-09-14 14:08:38 +000032 argv++;
Denis Vlasenkof6f43df2006-10-11 22:16:56 +000033 if (strchr(*argv, '/')) {
34 if (execable_file(*argv)) {
35 puts(*argv);
36 continue;
Denis Vlasenko01c27fc2006-10-05 21:10:53 +000037 }
Eric Andersen514633b2003-10-22 10:38:22 +000038 } else {
Denis Vlasenkof6f43df2006-10-11 22:16:56 +000039 p = find_execable(*argv);
40 if (p) {
41 puts(p);
42 free(p);
43 continue;
Erik Andersen330fd2b2000-05-19 05:35:19 +000044 }
Erik Andersen330fd2b2000-05-19 05:35:19 +000045 }
Denis Vlasenko01c27fc2006-10-05 21:10:53 +000046 status = EXIT_FAILURE;
Erik Andersen330fd2b2000-05-19 05:35:19 +000047 }
Denis Vlasenkof6f43df2006-10-11 22:16:56 +000048
Denis Vlasenkof0ed3762006-10-26 23:21:47 +000049 fflush_stdout_and_exit(status);
Erik Andersen330fd2b2000-05-19 05:35:19 +000050}