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

I need a bash script to read the data stream from the serial port (RS232 adapter for USB - port: / dev / ttyUSB0). Data should be stored line by line in the file until a specific input appears (for example, "eof"). I can provide any external input to the serial port. So far I have been using cat to read data, which works great.

cat /dev/ttyUSB0 -> file.txt 

The problem is that I need to finish the command myself by typing cntr + C, but I don’t know exactly when the data stream ends and the ttyUSB0 file does not transfer 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 an error "command not found"):

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

Does anyone have a convenient opportunity for my problem?

+6
source share
1 answer

Try awk(1) :

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

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

+5
source

All Articles