Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 544
user1822048 Avatar asked Nov 15 '12 10:11

user1822048


1 Answers

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

like image 142
Aaron Digulla Avatar answered Sep 20 '22 23:09

Aaron Digulla