update_out 444 B

123456789101112131415161718192021
  1. #! /bin/bash
  2. # Run given command application and update the contents of a given file.
  3. # Will not change the file if its contents has not changed.
  4. [[ $# -gt 1 ]] || { echo "Usage: ${0##*/} FILE COMMAND" >&2; exit 1; }
  5. set -u
  6. declare -r outfile="$1"
  7. shift
  8. if [[ ! -f $outfile ]]; then
  9. $@ >$outfile
  10. exit
  11. fi
  12. declare -r newout=${outfile}.new
  13. $@ >$newout
  14. rc=$?
  15. if cmp -s $newout $outfile; then
  16. rm $newout
  17. else
  18. mv -f $newout $outfile
  19. fi
  20. exit $rc