Ubuntu – How, in a script, can I determine if a file is currently being written to by another process

bashopenoffice.orgprocess

I'm very new to bash scripting, so I might be barking up the wrong tree, but here is my current situation:

In a script, I start soffice; to convert an odt to a pdf

It seems that soffice detaches itself from the script's process, and wanders off to do its own thing.. Okay, that's fine; GUI apps tend to do that …

However I need to wait until the new pdf has been fully written, as my next step involves processing that new pdf.

(As far as I know) I can't utilize soffice's process-ID, because it may have already been a running process before my script started: eg. soffice may be already open for normal GUI activity for another unrelated document/presentation/spreadsheet.

The crux of the matter for me is that before I can proceed, the writing of the new pdf must be finalized…

Is there some way to determine when a file is no longer open to another process in "write" mode? …

Best Answer

You can use lsof | grep /absolute/path/to/file.txt to see if a file is open. If the file is open, this command will return status 0, otherwise it will return 256 (1).

Be aware that this command will take a second since there are, normally, a lot of files open at any time.

You can also use lsof -c gedit, for example, to see which file gedit has opened. Restricting the output to one process will reduce execution time to practically nought.

Here's a script to wait:

#!/bin/bash

while :
do
    if ! [[ `lsof -c python3.2 | grep test.py` ]]
    then
        break
    fi
    sleep 0.5
done
echo "done"

This runs while a process 'pyhton3.2' has got the file 'test.py' opened. As soon as the file is closed, it moves on to 'echo done' and exits.

I've put 'sleep 0.5' in there so that the loop doesn't hog the CPU all that badly. Otherwise, it will use 100% cpu.

Bonus There seems to be an easy way to convent odt to pdf:

Thanks to scls19fr on the OOo Forum for this lovely tip. You can convert OpenOffice Writer files to PDF from the command line using unoconv -f pdf input.odt To get unoconv, simply run sudo apt-get install unoconv at the terminal. (rhyshale of rhyshale.wordpress.com)