Fabian
Fabian

Reputation: 13

Having trouble writing a Bash script that checks if a directory is empty and deletes it if it is

The Script is searching for files older than x, copies the files and parent directories into a new directory and deletes the sources files + directory if its empty. If it is empty, it changes into the dir above and checks again.

Copying files and dirs works, also deleting the files works but checking if the dir is empty does not, they just remain empty.

#!/bin/bash
SOURCE=/root/Desktop
DESTINATION=/Backup
find $SOURCE -type f -amin +1 -exec ./move_file.sh {} $DESTINATION \;

move_file.sh

#!/bin/bash
PFAD=`dirname $1`
mkdir -p $2$PFAD
cp $1 $2$1
rm $1
while [ `ls -a $PFAD | wc -l` -le 2 ]
do
echo $PFAD ist leer und wird gelöscht
rmdir $PFAD
$PFAD=`echo $PFAD | rev | cut -d/ -f2- | rev`
done

The Problem should be in the while loop.

Upvotes: 1

Views: 128

Answers (2)

ikettu
ikettu

Reputation: 1203

Something like

while [ "$(ls -A $PFAD)" ]

Simplest way to check empty directory

[ "$(ls -A /x/y/z)" ] && echo "Is Not Empty" || echo "Is Empty"

Upvotes: 1

Wintermute
Wintermute

Reputation: 44023

rmdir will not delete a directory that's not empty, so you can do the check and removal in one go with

while rmdir "$PFAD" 2>/dev/null; do
  echo "$PFAD ist leer und wird gelöscht"
  PFAD="$(dirname "$PFAD")"
done

The 2> /dev/null is there to suppress the error message you get if a directory is not empty and rmdir refuses to delete it because of that.

Note that the dollar sign at the beginning of

$PFAD=`echo $PFAD | rev | cut -d/ -f2- | rev`

is a problem in that it assigns the output of the command to a variable named after the contents of $PFAD. It could be solved by removing the dollar sign, but dirname is meant to deal with directories and better suited to the task. You should probably take care to test for . though, in case you use relative paths and the current working directory ends up empty, and possibly /. Although, if / ends up empty, the script will run into trouble before the infinite dirname loop becomes a problem.

Upvotes: 0

Related Questions