Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shellscript action if two files are different

Tags:

I am importing a file to my server using this command:

scp zumodo@shold:/test/test/test/server.py /test/test/test/test.py~/; 

I want to restart my server if the newly imported file test.py~ differs from the test.py that already exists. How would I do this using a shellscript?

like image 351
Spencer Avatar asked Nov 15 '11 16:11

Spencer


People also ask

How can I tell if two files are different?

Use the diff command to compare text files. It can compare single files or the contents of directories. When the diff command is run on regular files, and when it compares text files in different directories, the diff command tells which lines must be changed in the files so that they match.

How do I compare two files with a shell script?

#1) cmp: This command is used to compare two files character by character. Example: Add write permission for user, group and others for file1. #2) comm: This command is used to compare two sorted files. One set of options allows selection of 'columns' to suppress.

How do I tell if two files are identical in terminal?

If you all you want to know is whether two files are the same, use the -s (report identical files) option. You can use the -q (brief) option to get an equally terse statement about two files being different.

How do I compare the contents of two files in bash?

Bash Conditional Expressions File comparison If you want to compare two files byte by byte, use the cmp utility. To produce a human-readable list of differences between text files, use the diff utility.


1 Answers

if ! cmp test.py test.py~ >/dev/null 2>&1 then   # restart service fi 

Breaking that down:

  • cmp test.py test.py~ returns true (0) if test.py and test.py~ are identical, else false (1). You can see this in man cmp.
  • ! inverts that result, so the if statement translates to "if test.py and test.py~ are different".
  • The redirects >/dev/null 2>&1 send all output of cmp to null device, so you just get the true/false comparison result, without any unwanted noise on the console.
like image 181
Andrew Schulman Avatar answered Sep 29 '22 14:09

Andrew Schulman