1

When I am running following code:

#!/bin/bash

PREVIOUS_COMMIT=e099d95d52b8fca99e47fd7cee5f782287178b27
SERVICE=service-web-prj1

if [ ! git diff "$PREVIOUS_COMMIT" HEAD --name-only | grep -qs "$SERVICE" ] || [ ! git diff "$PREVIOUS_COMMIT" HEAD --name-only | grep -qs 'service-web' ];
    then
        echo Didnt pass first
        exit 0;
fi

echo passed first with $SERVICE

if ( ! echo "$SERVICE" | grep -q "^service-web" );
    then
        echo Didnt pass second
        exit 0;
fi

echo passed second with $SERVICE

I am getting:

scripts/getLastCommit.1.sh: line 9: [: missing `]'
scripts/getLastCommit.1.sh: line 9: [: missing `]'

I looked around and everyone mention the space before the last "]" Which I have tripled check and I do have that

Anyone knows what I am doing wrong?

Thanks, Dennis

Figured out that this will do the trick for me:

if ! echo $GITDIFF | grep -q -e 'service-web*' -e $SERVICE;
DThisner
  • 11
  • 2

1 Answers1

2

You can't test whole commands within the shell test brackets. You want to remove those brackets altogether which will cause it to simply test the exit code of the commands.

#!/bin/bash

PREVIOUS_COMMIT=e099d95d52b8fca99e47fd7cee5f782287178b27
SERVICE=service-web-prj1

if ! git diff "$PREVIOUS_COMMIT" HEAD --name-only | grep -qs "$SERVICE" || ! git diff "$PREVIOUS_COMMIT" HEAD --name-only | grep -qs 'service-web'
then
        echo "Didn't pass first"
        exit 0
fi

echo passed first with "$SERVICE"

if ( ! echo "$SERVICE" | grep -q "^service-web" )
then
        echo "Didn't pass second"
        exit 0
fi

echo passed second with "$SERVICE"
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
jesse_b
  • 37,005
  • Shouldn't ! echo | grep be echo | ! grep? Likewise with the first if. The return status of echo is not being used anyway, so why invert it... – Kusalananda Jun 09 '18 at 18:06
  • The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled. If the reserved word ‘!’ precedes the pipeline, the exit status is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value. – jesse_b Jun 09 '18 at 18:13
  • Hmm... yes. It's just looks counterintuitive to have if ! ... | grep instead of if ... | ! grep, but ok. – Kusalananda Jun 09 '18 at 18:23
  • Thanks @Jesse_b, worked :) now it is not working the way I want it to, will look into that now. I am thinking about making the "git diff" into a variable instead, to make less of a big heap of command. – DThisner Jun 09 '18 at 18:31
  • @SweKilt Related: https://unix.stackexchange.com/questions/444946/how-can-we-run-a-command-stored-in-a-variable – Kusalananda Jun 09 '18 at 18:53