Q:

Redirect bash output to file every 1 second

I want to redirect the output of the command tcptrack -i wlp3s0 to a log file every 1 second.
For that I found this script:
#!/usr/bin/env bash

file="file_$((SECONDS / 10))0.txt"        # calculate our initial filename
exec 3>"$file"                            # and open that first file

exec 4< <(echo <password>|sudo -S tcptrack -i wlp3s0)                  # also open a stream coming from nc on FD #4

while IFS= read -r line <&4; do           # as long as there's content to read from nc...
  sleep 1
  printf '%s\n' "$line" >&3               # write our line to whichever file is open on FD3
done

The script works fine except that I got weird output:
[?1049h[22;0;0t[1;53r(B[m[4l[?7h[?1h=[H[2Jl(B[0;7m Client [15bServer [15bState [7bIdle A Speed [8b
[52d TOTAL [58b0 B/s [8b
 Connections 0-0 of 0 [24bUn(B[0;4;7mp(B[0;7maused  Un(B[0;4;7ms(B[0;7morted [14b[53;65H(B[me(B[0;7m (B[mn(B[0;7m (B[mo(B[0;7m (B[mv(B[0;7m (B[mo(B[0;7m (B[m[H
 1**.***.*1*.*4*:****    ***.***.***.***:****    ESTABLISHED  0s   * 0 B/s[53;14H(B[0;7m1-1 of 1[53;65H(B[m[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;51r[2;1HM[1;53r[2;2H***.***.**.**:*****    ***.***.***.***:****[46GSYN_SENT     0s     0 B/s[53;16H(B[0;7m2 of 2[53;65H(B[m[2;46HESTABLISHED[64G*[53;65H[2;64H [53;65H[3;64H*[53;65H[3;64H [53;65H[3;64H*[53;65H[3;64H [53;65H[3;64H*[53;65H[3;64H [53;65H[3;64H*[53;65H[3;64H [53;65H
[4d ***.***.***.***:*****    ***.***.***.***:******[46GSYN_SENT     0s     0 B/s[53;16H(B[0;7m3 of 3[53;65H(B[m[3;64H*[53;65H[3;64H [53;65H[3;64H*[53;65H[3;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[3;64H*[4;49H|ACK-ACK[64G*[53;65H[3;64H 
 [53;65H[4;46HESTABLISHED[64G*[53;65H[4;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*[53;65H[2;64H [53;65H[2;64H*  

PS: I replaced the IP addresses with * .
How to fix the output to be as the command's output on the terminal?

A:

tcptrack is a ncurses-based tool, I don't think it makes sense to try capturing its output - what you see are the escape sequences. I think if you do netstat -t every second, you would get a log very similar to what you are trying to achieve.
(Btw., you might want to add yourself as "NOPASSWD" sudoer for netstat.)

