blob: 7a11bf7876839390cb9a8f2b266427e4b9f57c76 [file] [log] [blame]
Erik Andersen330fd2b2000-05-19 05:35:19 +00001/* vi: set sw=4 ts=4: */
2/*
3 * Which implementation for busybox
4 *
5 * Copyright (C) 2000 by Lineo, inc.
6 * Written by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 *
22 */
23
24#include "internal.h"
25#include <stdio.h>
Pavel Roskinc389d912000-06-05 23:41:27 +000026#include <sys/stat.h>
27#include <sys/param.h>
Erik Andersen330fd2b2000-05-19 05:35:19 +000028
29
30extern int which_main(int argc, char **argv)
31{
Pavel Roskinc389d912000-06-05 23:41:27 +000032 char *path_list, *test, *tmp, *path_parsed;
33 char buf[PATH_MAX];
34 struct stat filestat;
35 int count = 0;
Erik Andersen330fd2b2000-05-19 05:35:19 +000036
Pavel Roskinc389d912000-06-05 23:41:27 +000037 if (argc <= 1 || **(argv + 1) == '-') {
Erik Andersen330fd2b2000-05-19 05:35:19 +000038 usage("which [COMMAND ...]\n"
39#ifndef BB_FEATURE_TRIVIAL_HELP
40 "\nLocates a COMMAND.\n"
41#endif
42 );
43 }
44 argc--;
45
46 path_list = getenv("PATH");
47 if (!path_list)
48 path_list = "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin";
49
Pavel Roskinc389d912000-06-05 23:41:27 +000050 path_parsed = malloc (strlen(path_list) + 1);
51 strcpy (path_parsed, path_list);
52
53 /* Replace colons with zeros in path_parsed and count them */
54 count = 1;
55 test = path_parsed;
56 while (1) {
57 tmp = strchr(test, ':');
58 if (tmp == NULL)
59 break;
60 *tmp = 0;
61 test = tmp + 1;
62 count++;
63 }
64
65
66 while(argc-- > 0) {
67 int i;
68 int found = FALSE;
69 test = path_parsed;
70 argv++;
71 for (i = 0; i < count; i++) {
72 strcpy (buf, test);
73 strcat (buf, "/");
74 strcat (buf, *argv);
75 if (stat (buf, &filestat) == 0
76 && filestat.st_mode & S_IXUSR)
77 {
78 found = TRUE;
79 break;
Erik Andersen330fd2b2000-05-19 05:35:19 +000080 }
Pavel Roskinc389d912000-06-05 23:41:27 +000081 test += (strlen(test) + 1);
82 }
83 if (found == TRUE)
84 printf ("%s\n", buf);
85 else
86 {
87 printf ("which: no %s in (%s)\n", *argv, path_list);
88 exit (FALSE);
Erik Andersen330fd2b2000-05-19 05:35:19 +000089 }
90 }
91 exit(TRUE);
92}
93
94/*
95Local Variables:
96c-file-style: "linux"
97c-basic-offset: 4
98tab-width: 4
99End:
100*/