I'm working on a Bash function to search a directory for files that are either photos or videos, and I want to ensure that my approach is sound. Here's my method: I define a list of file types I'm interested in, including various image and video formats. Then, I use a for loop to construct a command that searches for these files. However, I've received some feedback on it, and I want to know if there are any improvements or adjustments I should consider to make my code better or more efficient. Here's my code snippet:
iterate() {
types=(
jpg jpeg jpe png gif bmp tiff tif webp heic heif avif
mp4 m4v mov avi mkv webm flv mpeg mpg 3gp 3g2 mts m2ts
dng cr2 cr3 nef arw orf rw2 pef raf srw
)
expr=()
for t in "${types[@]}"; do
expr+=( -iname "*.$t" -o )
done
find . -type f ( "${expr[@]}" -false ) -print
}
5 Answers
I suggest debugging your script using `bash -x yourscript.sh` to trace what's happening when you run it. This can help identify issues like the trailing '-o' you mentioned.
Another way to optimize your script is by using a regex pattern. You can combine file types into a single string and use `grep` for matching. For example:
F="jpg|jpeg|png|gif|mp4|avi|..."
find . -type f | grep -P ".($F)$"
This could make your script cleaner!
You've got a good setup! Just be cautious about that trailing `-o`. You might want to negate any extra conditions properly. You could try using array slicing to drop the last element before executing your find command.
Your approach looks solid! I usually simplify it by removing the last '-o' after the loop. You can do this using `unset`. Here’s a version you might like:
types=( foo bar )
expr=()
for t in "${types[@]}" ; do
expr+=( -o -iname "*.$t" )
done
unset -v 'expr[0]'
# This results in a valid array without a trailing -o.
If you're okay with sacrificing some accuracy for cleaner code, you could consider using the `file` command with `find`. Like this:
find /path -type f -exec file --mime-type {} + | grep -E 'image|audio|video'
This method is more straightforward in some cases.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically