0

I'm writing a script to check if there actually is a directory that has content and a normal size, and see if there is a directory older then 36 hours, if not it should alert me.

However I'm having trouble using the directories as variable. When I execute the script it returns: ./test.sh: line 5: 1: No such file or directory. I tried ALLDIR=$(ls /home/customers/*/ as well but returned the same error.

What am I doing wrong? Below is the script.

Thanks a lot in advance!!

#!/bin/bash
ALLDIR=$(find * /home/customers/*/ -maxdepth 2 -mindepth 2)
for DIR in ${ALLDIR}
do
  if [[ $(find "$DIR" -maxdepth 1 -type d -name '*' ! -mtime -36 | wc -l = <1 ) ]]; then
  mail -s "No back-ups found today at $DIR! Please check the issue!" test@example.com
  exit 1
  fi
done

for DIR in ${ALLDIR}
do
  if [[ $(find "$DIR" -mindepth 1 -maxdepth 1 -type d -exec du -ks {} + | awk '$1 <= 50' | cut -f 2- ) ]]; then
  mail -s "Backup directory size is too small for $DIR, please check the issue!" test@example.com
  exit 1
  fi
done
Florius
  • 367
  • 1
  • 5
  • 17

1 Answers1

4

For a start, to loop through all directories a fixed level deep, use this:

for dir in /home/customers/*/*/*/

A pattern ending in a slash / will only match directories.

Note that $dir is a lowercase variable name, don't use uppercase ones as they may clash with shell internal/environment variables.

Next, your conditions are a bit broken - you don't need to use a [[ test here:

if ! find "$dir" -maxdepth 1 -type d ! -mtime -36 | grep -q .

If anything is found, find will print it and grep will quietly match anything, so the pipeline will exit successfully. The ! at the start negates the condition, so the if branch will only be taken when this doesn't happen, i.e. when nothing is found. -name '*' is redundant.

You can do something similar with the second if, removing the [[ and $() and using grep -q . to test for any output. I guess the cut part is redundant too.

chepner
  • 497,756
  • 71
  • 530
  • 681
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • Great answer! However `grep -q .` can't be used here as he is checking whether there are 'single' or 'no' outputs right. – Anubis Aug 01 '17 at 11:07
  • As I understand, they want to check whether at least one directory exists or not, so it should be fine. – Tom Fenech Aug 01 '17 at 11:09
  • Would you mind explaining why using lower case for variables? And is `[[` practically never used? – Florius Aug 01 '17 at 11:35
  • @Florius The lower case thing is covered well elsewhere, e.g. https://stackoverflow.com/q/673055/2088135. It's a good idea to use `[[` in many situations but this isn't one of them! `if` doesn't always go with `[` or `[[`, it works with any command. – Tom Fenech Aug 01 '17 at 11:49
  • 1
    https://stackoverflow.com/questions/36371221/bash-if-statement-too-many-arguments explains how `[` (and by extension also `[[`) isn't what you want here. – tripleee Aug 01 '17 at 13:20