lsof man page
Lsof returns a one (1) if any error was detected, including the failure
to locate command names, file names, Internet addresses or files, login
names, NFS files, PIDs, PGIDs, or UIDs it was asked to list. If the -V
option is specified, lsof will indicate the search items it failed to
So that would suggest that your
lsof failed for some other reason clause would never be executed.
Have you tried just moving the file while your external process still has it open? If the destination directory is on the same filesystem, then there should be no problems with doing that unless you need to access it under the original path from a third process as the underlying inode will remain the same. Otherwise I think
mv will fail anyway.
If you really need to wait until your external process is finished with the file, you are better to use a command that blocks instead of repeatedly polling. On Linux, you can use
inotifywait for this. Eg:
inotifywait -e close_write /path/to/file
If you must use
lsof (maybe for portability), you could try something like:
until err_str=$(lsof /path/to/file 2>&1 >/dev/null); do
if [ -n "$err_str" ]; then
# lsof printed an error string, file may or may not be open
echo "lsof: $err_str" >&2
# tricky to decide what to do here, you may want to retry a number of times,
# but for this example just break
# lsof returned 1 but didn't print an error string, assume the file is open
if [ -z "$err_str" ]; then
# file has been closed, move it
mv /path/to/file /destination/path
As noted by @JohnWHSmith below, the safest design would always use an
lsof loop as above as it is possible that more than one process would have the file open for writing (an example case may be a poorly written indexing daemon that opens files with the read/write flag when it should really be read only).
inotifywait can still be used instead of sleep though, just replace the sleep line with
inotifywait -e close /path/to/file.