0

I have a simple script in which I am trying to find if make some_target exists or not. In case it does not exist then print a statement and exit 1.

#!/bin/bash
set +ex
output=$(make -n some_target 2>&1 | head -1)
echo "$output"
if [ "$output" == "*No rule to make target*" ]; then
  echo "Target is not Present"
  exit 1
else
  echo "foo"  
fi

but it is throwing an error and going into else loop

make: *** No rule to make target 'some_target'.  Stop.
test.sh: 5: [: make: *** No rule to make target 'some_target'.  Stop.: unexpected operato                                                                                                  
foo
7
  • echo "$output" before you use it. I also suspect the asterisks in the test are being expanded as filename wildcards: note the some_target in the error message. They should be inside the quotes, not outside. Apr 10, 2020 at 8:59
  • It doesnt makes any difference, updated Question and output above Apr 10, 2020 at 9:09
  • You are testing for an exact match which there is not. That's why the else branch is taken. Try comparing to the exact message.
    – RudiC
    Apr 10, 2020 at 9:37
  • Right hand value may change so it is more of finding a substring inside a bigger string Apr 10, 2020 at 9:39
  • * will be literal if quoted.
    – Kusalananda
    Apr 10, 2020 at 9:57

2 Answers 2

1

I was able to find an answer with below:

#!/bin/sh
set +ex 
if make -n some_target 2>&1 | grep -m 1 "No rule to make target"; then
        echo "Target is not Present"
        exit 1
else
        echo "foo"
fi
2
  • set +ex is not needed as those shell options wouldn't be set by default anyway. The -m 1 option to grep could be replaced by -q unless you want to see the output of grep.
    – Kusalananda
    Apr 10, 2020 at 10:10
  • Thanks that would also work Apr 10, 2020 at 10:19
0

Pattern matching(*) is possible in bash logical operators ==, =, and != where the operand on the right is considered a pattern. So you can write your condition:

if [[ $output == *'No rule to make target'* ]]

to check if the answer contains No rule to make target.

This said, it could be more efficient to check the return code of make?

(*) This is the same basic pattern matching as done on file names. There is also a logical operator =~ that takes a regular expression.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .