Philipp
Philipp

Reputation: 62

Using FIND command in conjunction with an IF statement

I want to know, if my solution of finding a filename or "filetype" in conjunction with an if-statement is good practice? Maybe there's a safer/better way doing stuff like this?

#!/usr/bin/env bash
DIR="/home/user"
SUB_DIR="/Downloads"

if [[ -n "$(find $DIR$SUB_DIR -depth -type f -name '*.jpg' -print0 -quit 2>/dev/null)" ]]; then
  echo "Found JPG-File"
elif [[ -n "$(find $DIR$SUB_DIR -depth -type f -name '*.png' -print0 -quit 2>/dev/null)" ]]; then
  echo "Found PNG-File"
#... and much more elif statements
fi

-print0 - if there are white spaces in filename

-quit - first catch and than quit find command

I also use this line of code to exclude sub-folders from search:

if [[ -n "$(find $DIR$SUB_DIR -type d \( -path */RAW* -o -path */VIDEO* \) -prune -o -type f -name '*.jpg' -print0 -quit 2>/dev/null)" ]]; then
  echo "Some other stuff"
fi 

Upvotes: 1

Views: 1946

Answers (1)

KamilCuk
KamilCuk

Reputation: 141020

is good practice?

The $DIR$SUB_DIR is unquoted, so undergoes word splitting and filename expansion. Check your scripts with shellcheck.net to catch such mistakes.

Do not disable errors - 2>/dev/null - they may provide user with various hint why it fails - permission denied, dir does not exists, etc.

Do not use uppercase variables for local variables. Prefer to use lowercase varaibles.

Maybe there's a safer/better way doing stuff like this?

Check find exit status.

Remove -depth. Why use it?

Instead of printing the whole filename, print a dot. Or just anything. It will be shorter than the filename, so less memory will be used.

if tmp="$(find "$dir/$sub_dir" ... -print . -quit)" && [[ -n "$tmp" ]]; then

And, also see Test whether a glob has any matches in bash .

Upvotes: 2

Related Questions