help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to use redirection in a function so that the function callers do


From: Peng Yu
Subject: Re: How to use redirection in a function so that the function callers don't need to know such details?
Date: Mon, 6 Apr 2020 20:41:45 -0500

Thanks. I wasn't aware of the usage `{fd1}<&0`. Where is it documented
in man bash?

https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Redirections

$ cat ./main1.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -v
{
        echo "fd1 $fd1" >&2
} {fd1}<&0
$  ./main1.sh
{
        echo "fd1 $fd1" >&2
} {fd1}<&0
fd1 10


On 4/6/20, Koichi Murase <address@hidden> wrote:
> 2020-04-07 5:53 Peng Yu <address@hidden>:
>> Is there a smart way to solve this kind of conflict so that the
>> callers of the function don't need to know the details of the
>> redirection within the function?
>
> You can use {var}<&0 redirection.
>
> $ cat 1.sh
> set -o pipefail
>
> function f2 {
>   local fd1
>   cat "$1" | {
>     paste /dev/fd/$fd1 "$2" "$3"
>   } {fd1}<&0
> }
>
> seq 3 | {
>   seq 11 13 | {
>     seq 21 23 | {
>       f2 /dev/fd/$fd1 /dev/fd/$fd2 /dev/fd/$fd3
>     } {fd3}<&0
>   } {fd2}<&0
> } {fd1}<&0
>
> $ ./1.sh
> 1       11      21
> 2       12      22
> 3       13      23
>
> ----------
>
> Maybe you can create a utility function something like:
>
> function pipesubst {
>   local __command=$1; shift
>   local __index=1
>   while (($#)); do
>     __command="local fd$__index; $1 | {
>       pipe$__index=/dev/fd/\$fd$__index
>       $__command
>     } {fd$__index}<&0"
>     ((__index++))
>     shift
>   done
>   eval "$__command"
> }
>
> Then:
>
> function f3 {
>   local a=$1 b=$2 c=$3
>   pipesubst 'paste "$pipe1" "$b" "$c"' \
>             'cat "$a"'
> }
> pipesubst 'f3 "$pipe1" "$pipe2" "$pipe3"' \
>           'seq 3' \
>           'seq 11 13' \
>           'seq 21 23'
>
> --
> Koichi
>


-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]