Friday, December 02, 2022

Re: redirection puzzle

rsykora@disroot.org writes:
> Dear list,
>
> ...
>
> but this does not work:
>
> odin:~$ echo 1 | tee $(tty) | sed 's/1/2/'
> 2
> odin:~$
>
> I do not understand why...

The position of the tty command in the pipeline means that its
standard input is not the terminal:

$ echo $(tty)
/dev/ttyp8
$ echo | echo $(tty)
not a tty

You can either capture the output of tty separately or get ksh to
do the work itself:

$ foo=$(tty)
$ echo "$foo"
/dev/ttyp8
$ echo 1 | tee $foo | sed s/1/2/
1
2

or

$ stdsplit() {
> while IFS= read -r line; do
> eval echo '"$line"' >&$1
> echo "$line"
> done
> }
$ echo 1 | stdsplit 2 | sed s/1/2/
1
2

Leaving stderr alone (I couldn't help myself; that's why there's
an eval in there now):

$ exec 3>&1 # Must happen outside the pipeline
$ echo 1 | stdsplit 3 | sed s/1/2/
1
2
$ exec 3>&- # Or don't do this.

Matthew

No comments:

Post a Comment