Essentially I want to run a command and capture its output to a file:

some_cmd > /etc/myservice.conf

and I want to run a different command only if that results in the contents changing:

systemctl myservice reload

It should run with literally any difference:

  • Same data, different order
  • File doesn't yet exist or is empty
  • Extra newline added at end
  • New file is empty

I was thinking something similar to tee, for example:

echo "value=1" | overwritediff /etc/myservice.conf && systemctl myservice reload

I could do this with temp files and diff, just wondering if there's a cleaner way. Really it's fine if the answer is "no, write a script".

This is what I'll do otherwise:

some_cmd > /tmp/myservice.conf

diff /etc/myservice.conf /tmp/myservice.conf || (
  mv /tmp/myservice.conf /etc/myservice.conf && systemctl myservice reload

What about a simple shell script using sha1sum?



SUM1=$(sha1sum $FILE)
echo "value=$VALUE" > $FILE
SUM2=$(sha1sum $FILE)

if [[ ! $SUM1 == $SUM2 ]]; then
  echo "Different" #put your command here

When executing:

nxr ~ touch filetest
nxr ~ bash sumtest.sh 1 filetest
-> Different
nxr ~ bash sumtest.sh 1 filetest
nxr ~ bash sumtest.sh 2 filetest
-> Different

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.