Reading the OP's question, I noticed the pointed exclusion of methods relying on PATH
, and disregarded the obvious answer for which
(because that is precisely what it does). The which
program, by the way was originally a C-shell script although there are other implementations (FreeBSD, and bash for instance). Solaris, for instance, has a version little changed from 4.2BSD, and its manual page states
Both aliases and path are taken from the user's .cshrc file.
If you do not use C-shell, that original version of which
has limited usefulness. Because there is no standard version, the results (and capability of the tool) can vary from system to system. Some shells (such as ksh
) have similar features, but named differently, e.g., whence
in the case of ksh
(bash supplies the ksh alias type
but not the `whence keyword).
I do not use which
much, having better tools (conflict and path). But having ignored the obvious, the question as worded could easily pose a more interesting question: how can an application determine the directory from which another application was run. Not the obvious "where is the executable?", but "what was the working directory when the program was run?". There was a similar question recently dealing with relative pathnames.
On some of the systems which support the /proc
pseudo-filesystem, there is a cwd
node which gives the current working directory of a given process. The question Find out current working directory of a running process? goes into some detail regarding this.
xterm's optional feature "spawn-new-terminal" (added in patch #225 in 2007) uses this information to make a new terminal instance run in the same working directory as the user's current shell working directory.
A script could use this by starting with the process-id for the command in question, and inspecting the /proc
tree for the corresponding cwd
node.