每10秒将bash输出重定向到新文件

时间:2017-07-27 16:29:58

标签: linux bash shell

我有一个COM_port,我这样听:

nc -l -p 1234.

所以,我想将输出重定向到一个文件,每隔10秒就会重新定向到一个新文件。 我知道如何将流重定向到文件:

nc -l -p 1234 > file.txt

但是如何每隔10秒将流写入新文件? (前10秒为file_10.txt,第二个为file_20.txt,依此类推)。 我害怕从流量中丢失数据。 怎么可能这样做?

感谢。

1 个答案:

答案 0 :(得分:6)

#!/usr/bin/env bash
#              ^^^^- IMPORTANT! bash, not /bin/sh; must also not run with "sh scriptname".

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

exec 4< <(nc -l -p 1234)                  # 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...
  new_file="file_$((SECONDS / 10))0.txt"  # calculate the filename for the current time
  if [[ $new_file != "$file" ]]; then     # if it's different from our active output file
    exec 3>$new_file                      #   then open the new file...
    file=$new_file                        #   and update the variable.
  fi
  printf '%s\n' "$line" >&3               # write our line to whichever file is open on FD3
done