view toys/which.c @ 624:1e8b9acdafeb

Genericize llist code a bit: rename llist_free() to llist_traverse(), and no longer accept NULL as a synonym for free.
author Rob Landley <>
date Sun, 15 Jul 2012 17:22:04 -0500
parents d51be130fda2
line wrap: on
line source

/* vi: set sw=4 ts=4:
 * which.c - Find executable files in $PATH.
 * Copyright 2006 Rob landley <>
 * Not in SUSv3.


config WHICH
	bool "which"
	default y
	  usage: which [-a] filename ...

	  Search $PATH for executable files matching filename(s).

	  -a	Show all matches
#include "toys.h"

// Find an exectuable file either at a path with a slash in it (absolute or
// relative to current directory), or in $PATH.  Returns absolute path to file,
// or NULL if not found.

static int which_in_path(char *filename)
	struct string_list *list;

	// If they gave us a path, don't worry about $PATH or -a

	if (strchr(filename, '/')) {
		// Confirm it has the executable bit set, and it's not a directory.
		if (!access(filename, X_OK)) {
			struct stat st;

			if (!stat(filename, &st) && S_ISREG(st.st_mode)) {
				return 0;
			return 1;

	// Search $PATH for matches.
	list = find_in_path(getenv("PATH"), filename);
	if (!list) return 1;

	// Print out matches
	while (list) {
		if (!access(list->str, X_OK)) {
			// If we should stop at one match, do so
			if (!toys.optflags) {
				llist_traverse(list, free);

	return 0;

void which_main(void)
	int i;
	for (i=0; toys.optargs[i]; i++)
		toys.exitval |= which_in_path(toys.optargs[i]);