do shell script error: find

My folder contains the following files:

This script deletes all files containing ‘34’ except ‘abc-23456’ and returns ‘deleted’. However, it throws en error if no files are found.

do shell script "[[ $(find '/path/to/folder' -type f -name '*34*' '!' -name 'abc-23456' -exec rm {} \\; -print) ]] && echo 'deleted'"

The command works as expected when run from Terminal.

[[ $(find '/path/to/folder' -type f -name '*34*' '!' -name 'abc-23456' -exec rm {} \; -print) ]] && echo 'deleted'

What am I missing?

I think because you don’t need to run it in a subshell and redirecting stdout

do shell script "find '/path/to/folder' -type f -name '*34*' '!' -name 'abc-23456' -exec rm {} \\; -print && echo 'deleted'"

What you did was running it in a subshell and set the result (stdout) of the subshell in a expression which will return an error. To suppress errors you can use the or operator to do do something when find doesn’t return 0.

do shell script "find '/path/to/folder' -type f -name '*34*' '!' -name 'abc-23456' -exec rm {} \\; -print && echo 'deleted' || echo 'Nothing to delete'"

Awesome… Thanks DJ.

Actaully, I spoke too soon. The OR version returns path deleted when found and simply deleted when nothing is found.

Sorry, poor explanation from my side. The thing is that the first example is a solution to your problem to get rid of the error. The second example is to get rid of an error if find will throw one but find won’t throw an error when no files are found but when the given arguments are invalid for example. The "nothing to delete’ message is maybe a poor representation of what’s happening.

Ahhh… I see.

I got this to work too…

do shell script "if find '/path/to/folder' -type f -name '*34*' '!' -name 'abc-23456' -exec rm {} \\; -print | grep -q .; then echo 'deleted'; fi"

Nice it worked out for you:

In fact both are the same. Using an ‘if command1; then command2; fi’ is the same as an ‘command1 && command2’.
And ‘if command1; then command2; else command 3; fi’ is the same as ‘command1 && command2 || command3’.