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: Koichi Murase
Subject: Re: How to use redirection in a function so that the function callers don't need to know such details?
Date: Tue, 7 Apr 2020 09:10:58 +0900

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



reply via email to

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