From dc90e938124f74ad000ec64cad96b4399b2862b0 Mon Sep 17 00:00:00 2001 From: omrzk <193513049+omrzk@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:27:20 -0600 Subject: [PATCH] Document that which() skips empty PATH components An empty component in PATH, from a leading, trailing, or doubled colon, means the current directory to execvp() and the shell. which() has always skipped them, but nothing said so, or kept it that way. Say so in the API description and add tests for it. A caller that wants the current directory searched must list it, e.g., as ".". Closes #27 --- src/which.c | 3 +++ test/which.c | 37 ++++++++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/which.c b/src/which.c index 45e5a38..332c916 100644 --- a/src/which.c +++ b/src/which.c @@ -49,6 +49,9 @@ static char *strip_args(char *path) * Like which(1), or `command -v foo` * @param cmd Command to look for in $PATH * + * Empty components in $PATH are skipped, they do not mean the current + * directory. To search it, list it, e.g., as ".". + * * @returns A malloc()'ed path to @a cmd on success, or @c NULL. */ char *which(const char *cmd) diff --git a/test/which.c b/test/which.c index 8e8d8c8..653e528 100644 --- a/test/which.c +++ b/test/which.c @@ -6,6 +6,41 @@ struct tc { int res; }; +/* Empty PATH components are skipped, they do not mean current directory */ +static int empty(void) +{ + const char *cmd = "executable"; + char *path[] = { + "", + ":", + ":/nonexistent", + "/nonexistent:", + "/nonexistent::/nonexistent", + NULL + }; + int result = 0; + size_t i; + + if (chdir("data/which")) + return 1; + + for (i = 0; path[i]; i++) { + setenv("PATH", path[i], 1); + if (whichp(cmd)) { + fprintf(stderr, "%20s : found in cwd with PATH='%s'\n", cmd, path[i]); + result++; + } + } + + setenv("PATH", "/nonexistent:.", 1); + if (!whichp(cmd)) { + fprintf(stderr, "%20s : not found with . in PATH\n", cmd); + result++; + } + + return result; +} + int main(void) { int result = 0; @@ -38,7 +73,7 @@ int main(void) for (i = 0; test[i].cmd; i++) result += test[i].exp != test[i].res; - return result; + return result + empty(); } /**