Reputation: 47
I have a script like this,
#!/bin/bash
echo "hello" > a.txt
while [ True ]; do
#do something here, very long and possiblely causing system reboot
done
It looks like I can only get a normal a.txt (with "hello" inside) if the execution is ended normally. In the case that the "while loop" is running or a system reboot was triggered during the while loop, there will be a blank a.txt.
By Google searching, it seemed to be a line-bufferring issue as shell turns on line bufferring by default. As there is no "Expect" or "stdbuf" installed on my customized Ubuntu, I tried to replace
echo "hello" > a.txt
with a Perl/C program, where line buffer is disabled. In Perl, I used "$|" and "fflush" was used in C. Unfortunately, it doesn't work.
Any feedback is appreciated...
Upvotes: 1
Views: 2614
Reputation: 167
Try if it works:
#!/bin/bash
echo "hello"|awk '{print;fflush()}' > a.txt
sync
while [ True ]; do
#do something here, very long and possiblely causing system reboot
done
Upvotes: 2
Reputation: 361595
That's not exactly true. After the echo the file will be written and visible to other programs. That is guaranteed.
What you might be seeing is that the file is not written to the physical disk at this point. That can happen due to the OS's filesystem buffering. Just because the file has been written to and other programs see it doesn't mean that it's been written out to disk. It could just be in memory.
You can request the OS to flush all buffered writes disk with the "sync" command. Try calling that before triggering the reboot to see if that solves your problem.
The sync utility can be called to ensure that all disk writes have been completed before the processor is halted in a way not suitably done by shutdown(8).
Upvotes: 3