Knowledgebase

How to compare files and folders via SSH

Comparing file differences through SSH, and also comparing the contents of directories can easily be performed with the command diff. For example:

diff example.txt example2.txt

will compare the files example.txt and example2.txt which are both in the current working directory. Of course, if the files are in different folders on your hosting account you can use the full paths to the files (e.g. diff /home/username/public_html/docs/example.txt /home/username/public_html/example2.txt). When you execute the command, if there are any lines in the files that are different, they will be listed. For example, let's say that we think that the above mentioned two example files are identical, but we're not exactly sure so we check by executing the command. Then we get the following output:


1c1
< Tis is an example file.
---
> This is an example file.
3c3
< Another line of this file.
---
> another line of this file.

In this case we can see that there are two lines in the files that are different. The lines in the first file that we put in the command (e.g. example.txt) have an opening bracket < in front of them. The lines from the second file (example2.txt) have a closing bracket > in front of them. They are separated by three hyphens. In our example the first line in the first file is different from the same line in the second file because of a spelling mistake (Tis instead of This). The third line in the second file begins with a lower case letter as compared to the same line in the first file (e.g. another instead of Another).

Of course, you can compare other types of files, not just txt files (e.g. PHP files, for example). There are also some useful options. For example, -b is for ignoring differences in terms of spaces, -w is for ignoring tabs and spaces, and -i is for ignoring case differences. So with the above example, if we use the command diff -i example.txt example2.txt, the second difference between the files (e.g. another-Another) won't be listed since it's a case difference. If the files are identical, no output will be shown. In case, you want explicitly to be informed that the files are the identical, you can use the option -s (e.g. diff -s example.txt example2.txt).

Directories are compared with the same command. For example:

diff folder folder2

will compare the directories folder and folder2 that are in the current working directory. They are compared in terms of their contents. If there are directories and/or files that are present only in one of the folders, they will be listed as being only in that folder.

Was this answer helpful?

 Print this Article

Also Read