0

I have a certain file UPDATE.sh. The task of this file is to update my program using git merge.

UPDATE.sh:

#!/usr/bin/env bash

git fetch https://xxxxx

newUpdatesAvailable=`git diff HEAD FETCH_HEAD`

if [[ "$newUpdatesAvailable" != "" ]]
then
        git branch backup
        git checkout backup
        git add .
        git add -u
        git commit -m date "+%d.%m.%Y"
        git checkout master

        git merge FETCH_HEAD
else
        echo "No updates..."
fi

I have to write the same thing but on Make syntax.

I tried to figure out the conditions in Make, but it didn't work out for me.

Please tell me how to write this correctly in Makefile without using:

update:
      ./UPDATE.sh
HajokElos
  • 21
  • 3
  • Does this answer your question? [Basic if else statement in Makefile](https://stackoverflow.com/questions/58602758/basic-if-else-statement-in-makefile) – oguz ismail Nov 21 '19 at 21:23

2 Answers2

0

You don't need to capture the output of git diff; you just need to know if there is a diff or not. Use the -q option.

if ! git diff -q HEAD FETCH_HEAD; then
  git branch backup
  ...
else
  echo "No updates"
fi        

-q suppresses output and implies --exit-code, which causes git diff to exit with a non-zero exit status if there are differences.

In a Makefile, this would be

.PHONY: update

update:
        git fetch https://xxxxx
        if ! git diff -q HEAD FETCH_HEAD; then \
          git branch backup && \
          git checkout backup && \
          git add . && \
          git add -u && \
          git commit -m date "+%d.%m.%Y" && \
          git checkout master && \
          git merge FETCH_HEAD; \
        else \
          echo "No updates"; \
        fi

The semicolons and backslashes are necessary because the entire if statement has to appear on one logical line.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • For sake of reliability I would add `.PHONY: update` for the update not to be skipped by an existing file named `update`. I would also add `set -e;` before `if` to let the shell exit on first non-successful command instead of keeping making random changes. – raspy Dec 04 '19 at 15:17
  • I don't recommend using `set -e`, but I'll update the answer to short-circuit the chain of commands if any fail. – chepner Dec 04 '19 at 15:41
0

Another alternative, that does not require extensive quoting, semi-colons, etc, is to take advantage of the fact that make will stop executing a rule when the exit code is non zero.

This will usually result in easier to maintain Makefile, with simpler rules.

update:
        git fetch https://xxxxx
        git diff -q HEAD FETCH_HEAD || { echo "No Update" ; false ; }
        git branch backup
        git checkout backup
        git add .
        git add -u
        git commit -m date "+%d.%m.%Y"
        git checkout master
        git merge FETCH_HEAD
dash-o
  • 13,723
  • 1
  • 10
  • 37