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

14,077

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

Share:
14,077
user1822048
Author by

user1822048

Updated on June 07, 2022

Comments

  • user1822048
    user1822048 almost 2 years

    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?