0

I am trying to write my first bash script. It checks if a USB-to-Seria bridge and an USB-Storage device is connected and then starts writing the incoming data on the /dev/ttyUSB0 into a file on the attached storage device.

The problem is this part of my code:

{
    cat -v $SERIAL > $USBDRIVE/first_test.txt
} || {
    exit 0
}

It works as long the storage device and serial converter is connected. Cat writes the file continuously.

When I disconnect one of the devices an error occurs and my script exits. But the already written content in the file is also deleted.

I want to exit the script, close the written file and not lose the content.

Community
  • 1
  • 1
Rush
  • 31
  • 1
  • sorry, the file will be cleared only when I deattache the serial converter. – Rush Mar 29 '15 at 10:48
  • Does the script run once or multiple times? Is it perhaps triggered on device events? This script is going to empty the file each time it runs. – Etan Reisner Mar 29 '15 at 11:33
  • Thanks for your reply. I have solved the problem by changing the cat command to 'cat -v $SERIAL >> $USBDRIVE/first_test.txt ' to append and not overwrite existing file. Now it works. But I wonder why ;-D When there is no serial adapter attached, why does cat writes 'NULL' into the file and don't break the its execution? – Rush Mar 29 '15 at 11:44
  • 1
    The use of `>` will *immediately* truncate the file whether or not `cat` actually runs successfully. Try `echo test > /tmp/testfile; lkfjeflkje > /tmp/testfile; cat /tmp/testfile` and see what you get. The shell truncates the output file before it even tries to run the command in question. – Etan Reisner Mar 29 '15 at 11:50

0 Answers0