Reputation: 591
I need to be able to check if a filename with a certain string exists within a directory of files using bash. In this example I want to check if there are files that contain the date 20171101
in their filename:
[ -e "/path/to/data/dir/*20171101*" ] && echo true || echo false
When I use find *20171101*
within the directory it returns the files containing that date. However when I try the same method on the full path I get a binary operator expected
error. This is both for -e and find.
What I need is to be able to search files using a wildcard and the full path and echo true/false when the condition is met. There can be multiple files, but it should return true when at least 1 file is found that meets the condition. Furthermore I need to execute it in 1 line. Thanks!
Upvotes: 3
Views: 10891
Reputation: 249123
[ -n "$(find /path/to/data/dir -name '*20171101*' | head -1)" ] && ...
The quoting is important to prevent the shell from expanding it in the current directory. You need to use test -n
because find
alone won't tell you if it found matches or not. The head -1
stops when it finds a match, so you don't waste time looking for more.
Upvotes: 6