Re: sh(1): POSIX "Command Search and Execution"

RVP <[email protected]>
Newsgroups gmane.os.netbsd.devel.userlevel
Message-ID <[email protected]>
On Sun, 22 Sep 2024, Robert Elz wrote:

> ps: Of course, one can almost accomplish this with functions...
>
> PATH_TO_BASIC_UTILITIES=/usr/bin/-
> PATH_TO_ENHANCED_UTILITIES=/usr/bin/+
> -() { ${PATH_TO_BASIC_UTILITIES}/"$@" ; }
> +() { ${PATH_TO_ENHANCED_UTILITIES}/"$@" ; }
>
> and then use them as
> 	- cat ...
> 	+ ls
> instead of
> 	-/cat ...
> 	+/ls
>
> and in that the "cat" part *is* allowed to have '/' in its name.
>

If your shell is bash, and it allows `/' in function names, you can do this:

```
$ cat mk-funcs.sh
OIFS=$IFS
IFS=:
set -- $PATH
N=$#
IFS=$OIFS

# walk backwards through dirs to match PATH-search order.
#
while [ $N -gt 0 ]
do
 	(
 	eval d=\${$N}
 	cd "$d"
 	for f in */*
 	do	test -x "$f" || continue
 		printf '%s () {\n\tcommand "%s" "$@"\n}\n' "$f" "$d/$f"
 	done
 	)
 	N=$((N - 1))
done

$ mkdir /tmp/ip

$ cp /bin/echo /tmp/ip/.

$ cp /usr/bin/printf /tmp/ip/.

$ eval "$(PATH=$PATH:/tmp . ./mk-funcs.sh)"

$ ip/echo hello
hello

$ ip/printf '%s\n' world
world
```

Of course, if you add/delete/rename commands (or dirs. in PATH), you'll have
to recreate the functions again (`hash -r` equiv.).

-RVP
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.