Accidentally overwrote a binary file on Linux? Here is how to restore it

A shell script went wild due to some bug, and the script overwrote a binary file /bin/ping. Here is how tor restores it.



ADVERTISEMENTS



Easy way: copy it from another server

There are two ways to solve this problem.

Just scp file from another box running the same version of your Linux distribution:

$ sudo scp vivek@server1.cyberciti.biz:/bin/ping /bin/ping

Proper way: Search and reinstall package

First, query the package which provides FILE /bin/ping as per your Linux distro:

Debian/Ubuntu Linux user type

$ dpkg -S /bin/ping

iputils-ping: /bin/ping

Now just reinstall the iputils-ping package using apt-get command or apt command:

$ sudo apt-get --reinstall install iputils-ping

RHEL/SL/Scientific/Oracle Linux user type

$ yum provides /bin/ping

iputils-20071127-24.el6.x86_64 : Network monitoring tools including ping

Now just reinstall the iputils package using yum command:

$ sudo yum reinstall iputils

Fedora Linux user type

$ dnf provides /bin/ping

iputils-20161105-1.fc25.x86_64 : Network monitoring tools including ping

Now just reinstall the iputils package using dnf command:

$ sudo dnf reinstall iputils

Arch Linux user type

$ pacman -Qo /bin/ping

/usr/bin/ping is owned by iputils 20161105.1f2bb12-2

Now just reinstall the iputils package using pacman command:

$ sudo pacman -S iputils

Suse/OpenSUSE Linux user type

$ zypper search -f /bin/ping

Sample outputs:

Loading repository data... Reading installed packages... S | Name | Summary | Type --+---------+------------------------------------+-------- | ctdb | Clustered TDB | package i | iputils | IPv4 and IPv6 Networking Utilities | package | pingus | Free Lemmings-like puzzle game | package

Now just reinstall the iputils package using zypper command:

$ sudo zypper -S iputils

If everything else failed, try restoring the file from backup

The reason why you keep backups is here. It is time to restore that file from NAS server or tape device:

scp vivek@backup1.cyberciti.biz:/backups/server1.cyberciti.biz/snap/lastest/bin/ping /bin/ping

What can be done to avoid such problem in future?

Testing in a sandbox is an excellent way to prevent such problem. Care must be taken to make sure that variable has value. The following is dangerous:

echo "foo" > $file

Maybe something like as follows would help (see “If Variable Is Not Defined, Set Default Variable“)

file="${1:-/tmp/file.txt}"

echo "foo" > $file

Another option is to stop if variable is not defined:

${Variable?Error \$Variable is not defined}