The advantage of such a script is that the file can be recovered if the deletion was a mistake. The following bash shell script called “safdel.sh” using a turnkey menu to offer the following choices:

  • The user enters the file name to be deleted.
  • The name is checked to make sure the file exists and is an ordinary file. If not, the user is asked again for a file until a valid name is entered or the user exits.
  • If the file name is valid, the file will NOT be deleted permanently but will be moved to a directory called “dsave” in the user’s /home directory keeping the same name but with some extra numbers added to make sure the name is unique. The reason for making the file name unique because the user may delete several files with the same name from different directories, so it is necessary to add some characters to the file name to make sure it is unique.

Note: The directory dsave may not exist, so the script will check if “dsave” does not exist it will create it in the /home directory.
Hint: If the file name is read as fname, then it will be moved to the name $fname$$. The variable $$ is the process ID of the current shell and changes all the time that will guarantee that each file being deleted will be have a unique name.

# !/bin/bash
# MENU DRIVEN BASH SCRIPT CREATED BY Nathan Joseph (http://NJ180degree.net)
# CREATED ON FEBRUARY 25th 2010
# ISSUED UNDER THE GNU GPL (GNU GPL)
echo "Hello $USER, Welcome to NATHAN CONTROL MENU"
echo "The Date & Time is:"
date
function SAFEDEL {
	echo -e "Please enter a file name to be deleted"
	read FNAME
	if [ ! -d /home/dsave ]
	then
		mkdir /home/dsave
	else
		echo ""
fi
	if [ -f $FNAME ]
	then
		mv $FNAME  /home/dsave/$FNAME$$
		echo -e "The file $FNAME Has succesfully deleted"
	else
		echo -e "Error: The file $FNAME does NOT exists!"
fi
}
echo -e "Please choose from the following options by entering 0 or 1"
echo -e "1. Safely delete a file!"
echo -e "0. Exit"
read option
while [ "$option" != "0" ]
	do
		case $option in
			1) SAFEDEL ;;
			*) echo -e "Invaild choice, please choose from 0 or 1 only" ;;
			0) echo -e "Thanks for using my script.. you may change or modify it to suit your purposes : )"
			echo -e "0.Exit the program"
			exit 0
			 ;;
		esac
		echo -e "Please press return to go back to the main menu"
		read RETURN
		echo -e "Please choose from the following options by entering 0 or 1"
		echo -e "1. Safely delete a file!"
		echo -e "0. Exit"
			read option
	done
exit

Enjoy : )


  • Share/Bookmark