Redirect STDOUT to new window, STDERR to same new window and also a log file

耗尽温柔 提交于 2020-08-20 08:12:32

问题


I have this long process in a bash script (one of many) and so I'm experimenting with sending all output to a separate window to monitor, with any errors logged to errorlog.txt. For example:

rsync -vahPz foo@bar:/bigfolder/ ./ >> /dev/pts/4 2>> errorlog.txt

Trouble is that above doesn't display any errors on the separate window.

Is there a way to redirect errors to both my separate window at /dev/pts/4 and errorlog.txt, while still redirecting normal output to /dev/pts/4 too?

Something like:

rsyncblah >> /dev/pts/4 2>> errorlog.txt && /dev/pts/4

回答1:


You can use tee with process substitution, like this:

your_cmd 1> >(tee -a /dev/pts/2 >> out.log) 2> >(tee -a /dev/pts/2 >> err.log)

Alternatively, you can use the process substitution only for stderr - because it is needed - and redirect stdout, just as normal, through a pipe:

your_cmd 2> >(tee -a /dev/pts/2 >> err.log) | tee -a /dev/pts/2 >> out.log



回答2:


bash Open new window for input/output

1. Create a new window and trapping his pts id

exec {BACKFD}< <(:)
xterm -e bash -c "exec {CLOSEFD}<> <(:);
                  echo >/proc/$$/fd/$BACKFD \$\$ \$CLOSEFD \$(tty);
                  read -u \$CLOSEFD" &
read -u $BACKFD bpid bclose btty

same for using gnome-terminal:

exec {BACKFD}< <(:)
gnome-terminal -- bash -c "exec {CLOSEFD}<> <(:);
                  echo >/proc/$$/fd/$BACKFD \$\$ \$CLOSEFD \$(tty);
                  read -u \$CLOSEFD" &
read -u $BACKFD bpid bclose btty

xterm -e is to be replaced by:

gnome-terminal --  # for gnome
mate-terminal --   # for mate
konsole -e         # for KDE

and so on...

Note read -u \$CLOSEFD will ensure new window will stay open until we close them.

2. playing with new window

printf >$btty '%s\n' "Hello world!"
sleep 2
dialog --gauge >$btty <$btty 'Fill the tank' 20 60 < <(
    for i in {0..100};do echo $i;sleep .02;done)
clear <$btty >$btty

if dialog --yesno >$btty <$btty 'Do this match?' 20 60
  then echo yes
  else echo no
fi
clear <$btty >$btty

answer=$(
  dialog --menu 'Choose on of:' 20 60 12 a foo b bar c baz 2>&1 >$btty <$btty
)
echo You choose: $answer
clear <$btty >$btty

3. As requested, sharing output of a command in a log file AND new window:

exec {SHAREDOUT}> >(tee $btty >>/path/to/logfile)
exec {SHAREDERR}> >(tee $btty >>/path/to/errfile)

ls -ld /t{mp,nt} 2>&${SHAREDERR} >&${SHAREDOUT}

rsync -vahPz --log-file=/proc/self/fd/$SHAREDOUT 2>&${SHAREDERR} \
    foo@bar:/bigfolder/. /destpath/.

4. Closing window:

echo >/proc/$bpid/fd/$bclose


来源:https://stackoverflow.com/questions/56090071/redirect-stdout-to-new-window-stderr-to-same-new-window-and-also-a-log-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!