gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 11:31:21 24 4
gpt4 key购买 nike

我有一个 COM_port,我是这样听的:

nc -l -p 1234.

因此,我想将输出重定向到一个文件,每 10 秒重定向到一个新文件。我知道如何将流程重定向到文件:

nc -l -p 1234 > file.txt

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

谢谢。

最佳答案

#!/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

关于linux - 每 10 秒将 bash 输出重定向到新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45356335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com