I have a folder of about 350 images (they are scanned recipes). To make finding them easier, I have written a search program in bash shell script. I have bash version 3.2 on Mac OS X 10.8 Mountain Lion.
The basic idea of my program:
- Ask the user for search terms (using osascript).
- Search the file (names) for the search terms, using mdfind.
- Send the matching files to ln (through xargs).
- Make a hardlink of matching files in a "results" directory. This directory is contained within the same folder of images (this directory is cleaned at the beginning of the program).
What the directories look like:
+Recipes
-files
-files
-files
+.search
-search (shell script)
+results
-links
-links
Here's my code:
#!/bin/bash
#
# Search program for recipes.
# version 2
# Clean out results folder
rm -rf ~/Google\ Drive/Recipes/.search/results/*
# Display the search dialog
query=$(osascript <<-EOF
set front_app to (path to frontmost application as Unicode text)
tell application front_app to get text returned of (display dialog "Search for:" default answer "" with title "Recipe Search")
EOF)
# If query is empty (nothing was typed), exit
if [ "$query" = "" ]
then
exit
fi
echo "Searching for \"$query\"."
# Search for query and (hard) link. The output from 'ln -v' is stored in results
# 'ln' complains if you search for the same thing twice... mdfind database lagging?
results=$(mdfind -0 -onlyin ~/Google\ Drive/Recipes/ "$query" | xargs -0 -J % ln -fv % ~/Google\ Drive/Recipes/.search/results)
if [ "$results" ]
then
# Results were found, open the folder
open ~/Google\ Drive/Recipes/.search/results/
else
# No results found, display a dialog
osascript <<-EOF
beep
set front_app to (path to frontmost application as Unicode text)
tell application front_app to display dialog "No results found for \"" & "$query" & "\"." buttons "Close" default button 1 with icon 0
EOF
fi
It works fine—the first time. If you search for the same thing twice, it breaks.
Explanation: let's say I search for "chicken". 34 files match, and hard links are made in the results directory.
Now, I run the program again, and search for the same thing—"chicken". The directory is emptied (by rm
). But now, the finding/linking stops working—only 6 or 7 recipes will be linked. What seems to be happening is that mdfind
is finding the results in the search directory, after they have been deleted, and then ln
can't make links. But it doesn't find the main files...
I get
ln: ~/Google Drive/Recipes/.search/results/recipe.jpg: no such file or directory
I looked at mdfind used for creating symlinks not working as expected; they have a similar problem (but no help).
Thanks for any help... this has been annoying me for a long time.