I'm working on a Recycle Bin script which I can call to delete a file and restore a file.

The delete currently works fine and can be called using a wildcard, filename (for current directory) or a full filepath entirely. It then takes this file and stores it in /root/Dustbin/...

# del example.txt

While doing this it also stores the original filepath in a log.txt file in the Dustbin.

Now my question is this - how would I go about restoring the file to it's original location (which is stored in the log.txt file)?

My code for restore is currently:


for path in "$@"; do
find /root/Dustbin -name "$path" -exec mv {} ./ \;

#End of script

At the moment this restores the file specified from Dustbin to my current location using

# restore example.txt



Without more details on the log file it's hard to give an exact answer but here are some pointers.

Use grep to select the correct line from the log. Make sure to make the command specific enough so you get exactly one result by anchoring the search using things like the start of a line (^) or by matching whatever delimiters you use in your log.

Use awk or sed to read the path from the line the grep command returned. Again make sure to get the full path and only the elements of the path you need. (Watch out for whitespace etc.)

When specifying the target to restore again make sure to watch out for whitespace and other characters that might mess up the mv command by properly quoting the path. To avoid issues with dashes in the filename you could add -- after any options you wish to pass to the mv command. -- indicates the end of parameters for most commands.

Some additional thoughts:

  • If you place all deleted files in the same directory a find is not required you can simply mv from /root/Dustbin to the original location
  • However if you place all files without renaming them in the same directory you might end up overwriting files in your Dustbin
  • add sufficient error handling in both the delete and restore scripts
  • don't rely on a mechanism like this for important files! If you need to be sure that you can restore a specific file you need to make sure you have a proper backup available and that you made sure you can restore from it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.