Shellscript action if two files are different

Spencer picture Spencer · Nov 15, 2011 · Viewed 28k times · Source

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?

Answer

Andrew Schulman picture Andrew Schulman · Nov 15, 2011
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.