Based on this answer, I wrote the following which swaps file descriptors 1 and 2:
swap12
:
#!/bin/bash
"$@" 3>&1 1>&2 2>&3 3>&-
I can then operate on STDERR in a pipeline, eg:
$ swap12 ls -ld /tmp /ooooooo | tr o X
ls: cannXt access '/XXXXXXX': NX such file Xr directXry
drwxrwxrwt 19 root root 1400 Jul 1 17:14 /tmp
However swapping the FDs doesn't work multiple times:
$ swap12 ls -ld /tmp /ooooooo | swap12 tr o X | tr o Z
ls: cannXt access '/XXXXXXX': NX such file Xr directXry
drwxrwxrwt 19 root root 1400 Jul 1 17:14 /tmp
Above I'm expecting the 2nd swap12
to again swap STDOUT and STDRR, so the 2nd tr
would operate on ls
's original STDOUT. I'm expecting to see:
$ swap12 ls -ld /tmp /ooooooo | swap12 tr o X | tr o Z
ls: cannXt access '/XXXXXXX': NX such file Xr directXry
drwxrwxrwt 19 rZZt rZZt 1400 Jul 1 17:14 /tmp
How can I achieve what I'm after?
I have the feeling that my problem is due to changing the file descriptors in subshells. Would there be an advantage to implementation as zsh
global alias -g
alias? (But then how would the bash
implementation look?)