Bash syntax error when "else" follows an empty "then" clause
It seems that you want to do a no-op if the file is open so you should add a :
, which is a null command in bash
:
if lsof "$filename" > /dev/null; then
# file is open
:
else
printf 'deleting %s\n' "$filename"
rm -- "$filename"
fi
If you don't use :
, bash
can not parse you code, and will show error like bash: syntax error near unexpected token 'else'
.
Another alternative: reverse your logic.
if ! lsof "$filename" >/dev/null;then
echo "deleting $filename"
rm "$filename"
fi
Don't use command substitution on the output of find
. Here, everything can be done with find
:
find . -mtime 1 -type f ! -exec lsof -t {} \; -exec rm -f {} \; > /dev/null
With a few find
implementations (including FreeBSD find
where it comes from and GNU find
), you can use -delete
instead of -exec rm...
.
The reason you're getting an error is that there's no command between then
and else
and some shells (starting with the Bourne shell where that syntax comes from) require at least one (and a comment is not a command). Note that it is completely arbitrary and there is no reason why those shells would do that. yash
and zsh
don't have that limitation (if false; then else echo x; fi
and even if false; then else fi
work fine with them).
As others have said, you can use a noop command like :
(or for nothing in; do nothing; done
) or reverse the logic with the !
keyword (available in POSIX shells, but not the Bourne shell (you'll find that using :
for that was common in that shell)). mksh
and yash
happen to support if false; then () else echo x; fi
(I wouldn't rely on it as that could change in future versions though).
Another approach is with:
lsof... || {
cmd1
cmd2
}
though one difference is the overall exit status which will be that of lsof
if lsof
fails.