Mercurial > hg > toybox
comparison toys/other/which.c @ 653:2986aa63a021
Move commands into "posix", "lsb", and "other" menus/directories.
author | Rob Landley <rob@landley.net> |
---|---|
date | Sat, 25 Aug 2012 14:25:22 -0500 |
parents | toys/which.c@1e8b9acdafeb |
children | 6df4ccc0acbe |
comparison
equal
deleted
inserted
replaced
652:2d7c56913fda | 653:2986aa63a021 |
---|---|
1 /* vi: set sw=4 ts=4: | |
2 * | |
3 * which.c - Find executable files in $PATH. | |
4 * | |
5 * Copyright 2006 Rob landley <rob@landley.net> | |
6 * | |
7 * Not in SUSv3. | |
8 | |
9 USE_WHICH(NEWTOY(which, "<1a", TOYFLAG_USR|TOYFLAG_BIN)) | |
10 | |
11 config WHICH | |
12 bool "which" | |
13 default y | |
14 help | |
15 usage: which [-a] filename ... | |
16 | |
17 Search $PATH for executable files matching filename(s). | |
18 | |
19 -a Show all matches | |
20 */ | |
21 #include "toys.h" | |
22 | |
23 // Find an exectuable file either at a path with a slash in it (absolute or | |
24 // relative to current directory), or in $PATH. Returns absolute path to file, | |
25 // or NULL if not found. | |
26 | |
27 static int which_in_path(char *filename) | |
28 { | |
29 struct string_list *list; | |
30 | |
31 // If they gave us a path, don't worry about $PATH or -a | |
32 | |
33 if (strchr(filename, '/')) { | |
34 // Confirm it has the executable bit set, and it's not a directory. | |
35 if (!access(filename, X_OK)) { | |
36 struct stat st; | |
37 | |
38 if (!stat(filename, &st) && S_ISREG(st.st_mode)) { | |
39 puts(filename); | |
40 return 0; | |
41 } | |
42 return 1; | |
43 } | |
44 } | |
45 | |
46 // Search $PATH for matches. | |
47 list = find_in_path(getenv("PATH"), filename); | |
48 if (!list) return 1; | |
49 | |
50 // Print out matches | |
51 while (list) { | |
52 if (!access(list->str, X_OK)) { | |
53 puts(list->str); | |
54 // If we should stop at one match, do so | |
55 if (!toys.optflags) { | |
56 llist_traverse(list, free); | |
57 break; | |
58 } | |
59 } | |
60 free(llist_pop(&list)); | |
61 } | |
62 | |
63 return 0; | |
64 } | |
65 | |
66 void which_main(void) | |
67 { | |
68 int i; | |
69 for (i=0; toys.optargs[i]; i++) | |
70 toys.exitval |= which_in_path(toys.optargs[i]); | |
71 } |