Friday, January 18, 2013

How to Get Back Accidentally Deleted Files in Linux Using Simple Terminal Commands

Much to the delight of a Linux user, it takes only a little effort to recover an accidentally deleted file in Linux provided the file is still intact on the hard disk. If you have heard about file deletion in Windows, it has the same concept in Linux as well. When a file gets deleted from your Linux system, only a link to an inode on your disk is broken. This inode stores essential information with respect to the file. If the process that deleted the file still has it open, the inode cannot be used for writing. Thus, the deleted file can be recovered, but only for that fairly short time period. You can search for the directory corresponding to this process by running the command ‘ls /proc’. This will list all the currently running processes as directories along with their names or PIDs. To know the PID of a specific process, you can use the ‘ps’ command. After finding the process in /proc, you may collect the data from this directory and save it again. 

For instance, you have a file named ‘test_file’ that contains some text. Let us first delete this file and then recover it using the aforementioned approach:

  • Run the ‘less’ command to see the contents of ‘test_file’ as follows:
    less ~/test_file
  • Once the file is opened, press the ‘Ctrl’ and ‘z’ keys together. This will make the process a ‘zombie’.
  • Run the command ‘ls -l ~/test_file’ to see if the file is still there.
  • Next, delete the file with the command ‘rm ~/test_file’.
  • If you again check this file using the ‘ls’ command, you will find that the file is not there anymore. As you have zombied the command that was used to view the contents of the file, you can still recover this file from the data withheld.
  • Run the following command:
    ‘lsof | grep test_file’ 
  • This can make you wait for a while. In the end, you will be presented with something like:
    less 14675 zombie 4r REG 8,1 21 5127399 /home/zombie/test_file (deleted)
  • Get the PID of the file (i.e. value in the second column – ‘14675’) and its descriptor (in fourth column – ‘4’).
  • Run the below command to recover the file:
    ‘cp /proc/14675/fd/4 ~/recovered_file’
  • View the contents of the recovered file as follows:
    ‘less ~/recovered_file’

In case you fail to do a successful recovery, use professional data recovery Linux utilities. These software can rigorously scan your drive to recover every piece of valuable information from your Linux system.