Is This Bash For Loop Method for Finding Files Good Practice?

0
12
Asked By CuriousCoder99 On

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

Answered By CodeCritic88 On

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.

Answered By Codesmith_83 On

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!

Answered By PracticalProgrammer On

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.

Answered By BashBuddy123 On

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.

Answered By QuickFixGuru On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.