1#!/bin/bash 2# 3# Copyright 2017, Data61 4# Commonwealth Scientific and Industrial Research Organisation (CSIRO) 5# ABN 41 687 119 230. 6# 7# This software may be distributed and modified according to the terms of 8# the BSD 2-Clause license. Note that NO WARRANTY is provided. 9# See "LICENSE_BSD2.txt" for details. 10# 11# @TAG(DATA61_BSD) 12# 13 14# 15# Execute a command that generates a single output file. If the output file is 16# has unchanged contents, restore the old modification date to prevent GNU make 17# et. al. from continuing building down the dependency chain. 18# 19 20if [ $# -le 1 ]; then 21 echo "Usage: $0 <output file> <cmd> [<cmd args> ...]" 22 exit 1 23fi 24 25# Get the target file 26TARGET_FILE=$1 27shift 28 29# If the file doesn't exist, we always run the command. 30if [ ! -e $TARGET_FILE ]; then 31 V=$@ 32 sh -c "$V" 33 exit $? 34fi 35 36# Make a copy 37TMP_FILE=`mktemp /tmp/XXXXXXXX` 38cp -a $TARGET_FILE $TMP_FILE 39 40# Run the command 41V=$@ 42sh -c "$V" 43ERROR_CODE=$? 44 45# Restore the old file if the contents are the same. 46if cmp $TMP_FILE $TARGET_FILE > /dev/null 2> /dev/null; then 47 mv -f $TMP_FILE $TARGET_FILE 48else 49 rm -f $TMP_FILE 50fi 51 52# Return with the error code. 53exit $ERROR_CODE 54 55