Reputation: 21
I am fairly new to shell scripting, so go easy on me please as I know this is most likely something real basic. My question is this, I need to write a script that will look at a directory and tell me if it finds a match for a string that I specify in the filenames. Here would be an example.
I have a directory named tmp. Inside that directory are files named tmp-a, temp-a, temporary-a, etc. If the script looks at the directory and sees that there is a filename with the string of 'tmp', or 'temp' it should continue with the script, but if it does not see any filenames matching a string specified in the shell script it should quit. I am basically looking for a conditional 'if [ -f filename ]' statement that can apply 'or'.
I hope that made sense and as always, thanks in advance.
Tim
Upvotes: 2
Views: 885
Reputation: 107879
The pattern tmp*
expands to the list of files whose name begins with tmp
, or to the single-word list consisting of the literal pattern itself if there is no matching file.
set --
for pattern in 'tmp*' 'temp*'; do
set -- $pattern "$@"
if [ ! -e "$1" ]; then shift; fi
done
if [ $# -eq 0 ]; then
echo "No matching file"
else
for x in "$@"; do …; done
fi
In bash, you can request the expansion of a pattern that matches no file to be the empty list, which simplifies matters a lot.
shopt -s nullglob
set -- tmp* temp*
if [ $# -eq 0 ]; then …
The same thing goes for zsh, which allows this to be set per-pattern.
set -- tmp*(N) temp*(N)
if [ $# -eq 0 ]; then …
If you wish to search recursively inside directories, you can use the find
command.
if [ -n "$(find -name 'tmp*' -o -name 'temp*' | head -c 1)" ]; then
# there are matching files
fi
Upvotes: 3