Undo (cp) copy command in Linux/Ubuntu

Let’s say you’ve copied a giant chunk of data from a source to destination something like this:

sudo cp From_SOURCE/* To_DESTINATION/

Now you wish to undo this command. Phew!!!

Solution:

This can be achieved using a python script for nerds like us,

The script

#!/usr/bin/env python

import os

source_dir = "/path/to/source" # the folder you copied the files from
target_folder = "/path/to/destination" # the folder you copied the files to

for root, dirs, files in os.walk(source_dir):
    for name in files:
        try:
            os.remove(target_folder+"/"+name)
        except FileNotFoundError:
            pass

How to use this thing?

  • Paste the script in an empty file, save it as reverse.py,
  • Insert the correct paths for source and target folder,
  • Make it executable for convenience reasons,
  • Run it by the command: [sudo] /path/to/reverse.py

Warning

First try on a test directory, I’m guessing the damage might be negligible but on your risk again!

Second thing to note:-

In case the source directory has no sub-directories, the script can even be simpler:

#!/usr/bin/env python

import os

source_dir = "/path/to/source" # the folder you copied the files from
target_folder = "/path/to/destination" # the folder you copied the files to

for file in os.listdir(source_dir):
    try:
        os.remove(target_folder+"/"+file)
    except FileNotFoundError:
        pass

TL;DR:

All files that are present in both src and dest can be removed from dest like this:

find . -maxdepth 1 -type f -exec cmp -s '{}' "$destdir/{}" \; -exec mv -n "$destdir/{}" "$toDelete"/ \;

Akash Angle

I am a Full time Linux user who has quit using Windows for unknown reasons, making my life truly open source.

Recent Posts

Get the most juice from your ISP/router — setting MTU size & other handy tweaks

This is not an ad-vocation by any means for TP-link branding, however a real life…

6 months ago

How to make any Android phone up-to 3x faster – Developer options unleashed

First of all we need to hit the kernel version on any Android device. You…

6 months ago

systemd-resolve command not found in Ubuntu Desktop

Use resolvectl status instead. It's like something deprecates and suddenly things get broken! In systemd…

11 months ago

How to exclude multiple directories with rsync?

Geeky question: This is what people and friends have tried: rsync -arv --exclude "/home/john/.ccache:/home/ben/build" /home/john…

11 months ago

How to resolve apt-get -f not working

You might encounter this error which appears to be very common on Debian based Distro's…

11 months ago

How to install Broadcom STA wireless drivers on Kali Linux

PS: This article is for only Kali Linux users, that too having a Broadcom Wireless…

11 months ago