Sometimes it’s useful to trigger an action after a file is closed. Suppose you started a lengthy download on your notebook and you want to suspend it as soon as the download is done. There are several ways to achieve this.
If you started the download using a web browser like Chrome, the file will be renamed as soon as it is done. You can run a simple shell loop that waits until the file doesn’t exist anymore:
# while [ -e file.part1.zip ]; do sleep 1; done; pm-suspend
When downloading using a command line tool like wget
that doesn’t rename downloaded files, you can use the fuser
Linux utility to check if the downloaded file is still open. If it isn’t, the download is done:
# while fuser -s file.zip; do sleep 1; done; pm-suspend
Things get more complicated if there are multiple files involved and you want a solution that both handles file closes and renames. This is what I have come up with:
# sleep-while-open.sh file1 file2 file3; pm-suspend
And here’s the sleep-while-open.sh
script:
#! /bin/sh STATUS=open while [ $STATUS = open ]; do STATUS=closed for F in "$@"; do if [ -e "$F" ] && fuser -s "$F"; then STATUS=open fi done sleep 1 done
Note that for the pm-suspend
to work, you either have to run your commands in a root shell or use sudo
. Since you won’t be there to enter the password, you’ll need to give your user permissions to run /usr/sbin/pm-suspend
in /etc/sudoers
.