I have an Arduino sending data over a serial port to my Ubuntu PC. This is working as I can open a serial monitor on the PC and view the data. The arduino sends one line of data every 2 seconds. I want to redirect the output to a text file on the PC. I tried:

(stty raw; cat > /home/me/received.txt) < /dev/ttyUSB2

It works but it appends each line received to the file. I want it to over write the file each time. In other words, the file should only ever have one line of data in it which would be the newest received.

I thought the < vs << would take care of that but obviously I am missing something. Can anyone point me in the right direction?

  • < means redirect input from a file (by name) and << means from the current script/stdin. You presumably mean > versus >> which redirect output to the beginning of a file (truncate) or the end (append) when the process is started, but while the process runs it writes sequentially. – dave_thompson_085 Oct 18 '16 at 7:30
  • Yes, that is exactly what I was incorrectly thinking. Thanks for the clarification. – Adam Selene Oct 18 '16 at 11:45

I would try something like this:

(stty raw; while IFS= read -R line; do
printf '%s\n' "$line" > /home/me/received.txt; done) < /dev/ttyUSB2
  • Thanks. It didn't like the capital R. Changed it to lower case and works perfectly. Appreciate the help. – Adam Selene Oct 18 '16 at 11:43

Another possibility is to slightly abuse awk:

( stty raw; awk -v f="outfile" '{print >f; close(f)}' )<tty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.