jDataLab

1 minute read

Sometimes, the rm command will not remove certain files or subdirectories and it reports the error “rm: fts_read failed: No such file or directory”. Repeating the same rm command may eventually delete the directory.

The following bash script creates a new backup of a source directory; if the backup directory exists, remove the backup before copy.

./sample.sh /path/to/source /path/to/destination backup-directory-name

sample.sh

#! /bin/bash
source=$1 #source directory
destination=$2 #backup location 
dirname=$3 #name of the backup directory

if [ -d "$destination/$dirname" ]
then	
	echo 'yes'
	#change current working directory
	cd $destination
	echo $PWD
	#if the directory is not empty, repeat rm
	if [ -z "$(ls -A $dirname/)" ]; then
   		echo "Empty"
	else
   		echo "Not Empty"
		echo "start rm.."
		#remove files in a directory
		while [ ! -z "$(ls -A $dirname/)" ]
		do
			echo "repeat rm.."
			rm -rfv $dirname/*
		done
	fi
	#remove the empty directory
	rmdir $dirname	
fi
#make the copy
cp -r $source $destination