1

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 
Philipp
  • 27
  • 6
  • A safer way would be to also check the exit status you get from `find`. My `man` page says: "_find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find._" – Ted Lyngmo Jul 12 '21 at 10:10

1 Answers1

2

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 .

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • I thought, if I'm using the `-n` operator - which means the length of a string is greater than zero - I should't output errors because an error will also match the if-statement? – Philipp Jul 12 '21 at 14:55
  • 1
    The `$(...)` catches stdout. The stderr is still redirected to terminal. `[[ -n "$(echo "ERROR MESSAGE" >&2)" ]]` – KamilCuk Jul 12 '21 at 15:04