On Fri, Nov 22, 2024 at 08:00:41 +0100, Martin Schulte wrote:
> cat-opted-pipe() {
> cmd=$1
> shift
> while [[ $# -gt 0 ]]; do
> [[ $1 != cat ]] && cmd="$cmd | $1"
> shift
> done
> echo "$cmd"
> }
This approach only works for commands which are simplistic enough
that you can eval the resulting string safely. If one of your
commands contains a filename provided by an external source, for
example, you'd have to ensure that the filename is quoted in an
eval-safe way (${file@Q} or whatever).
On the plus side, your eval approach allows the commands to contain
redirections or compound commands.
Another approach, which may work in many cases, would be to hard-code
the logic for a specific number of commands.
Let's say you know there will always be either two or three commands
to be piped. Then instead of trying to "trick" things by setting one
of the commands to cat, you can selectively run a pipeline with the
correct number of commands:
# Arguments are array names which contain commands to be piped.
dispatch() {
local -n _disp1 _disp2 _disp3
case $# in
2) _disp1=$1; _disp2=$2
"${_disp1[@]}" | "${_disp2[@]}"
;;
3) _disp1=$1; _disp2=$2; _disp3=$3
"${_disp1[@]}" | "${_disp2[@]}" | "${_disp3[@]}"
;;
*) echo >&2 "dispatch: wrong number of args (must be 2 or 3)"
return 1
;;
esac
}
hobbit:~$ a=(echo "foo bar") b=(sed 's/o b/ob/')
hobbit:~$ dispatch a b
foobar
hobbit:~$ c=(rev)
hobbit:~$ dispatch a b c
raboof
Obviously this can be extended to any finite number of commands.
It doesn't rely on eval, so you don't have to @Q everything, but it
also means you can't slap a redirection inside the first command.
Then again, you could just do "dispatch a b < inputfile", so the lack
of internal redirections may not be an issue.