Bash script: save stream from Serial Port (/dev/ttyUSB0) to file until a specific input (e.g. eof) appears

主宰稳场 提交于 2019-11-30 05:03:58

问题


I need a bash script to read the data stream from a Serial Port (RS232 to USB adapter - Port: /dev/ttyUSB0). The data should be stored line by line in a file until a specific input (for example "eof") appears. I can give any external input to the Serial Port. Till now I use cat to read the data, which works fine.

cat /dev/ttyUSB0 -> file.txt

The problem is, that I need to finish the command myself by entering cntr+C, but I don't know exactly when the data stream ends and the ttyUSB0 file does not gerenate an EOF. I tried to implement this myself, but did not find a convenient solution. The following command works, but I don't know how to use it for my problem ("world" will create a "command not found" error):

#!/bin/bash
cat > file.txt << EOF
hello
EOF
world

The following code works for my problem, but it takes too much time (the data stream consists of ~2 million lines):

#!/bin/bash
while read line; do
     if [ "$line" != "EOF" ]; then
          echo "$line" >> file.txt
     else
          break
     fi
done < /dev/ttyUSB0

Has anyone a convenient possibility for my problem?


回答1:


Try awk(1):

awk `
/EOF/ {exit;} 
 {print;}` < /dev/ttyUSB0 > file.txt

This stops when it sees the line EOF and prints everything else to file.txt



来源:https://stackoverflow.com/questions/13395222/bash-script-save-stream-from-serial-port-dev-ttyusb0-to-file-until-a-specifi

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