Grep in BASH sub-shell drives me crazy

I’m sitting at a script and can’t wrap my head around the following issue.

echo "${PATH}" | grep -q "${testPath}"

Has a return value of 0.

pathIncluded="$(echo "${PATH}" | grep -q "${testPath}")"

The value of pathIncluded is 1.

Why?

I tested this issue thoroughly.
The sub-shell has the correct PATH and includes the testPath, as expected.

I feel like it has something to do with this example of how to test with grep:
https://mywiki.wooledge.org/BashPitfalls#if_.5Bgrep_foo_myfile.5D

But this does not answer, why my variable is holding the value 1… What’s so special about grep in this case?

When I try this in a script, I don’t get the value 1 out of $pathIncluded, it’s just empty. When I use:

pathIncluded="$(echo "${PATH}" | grep -q "${testPath}")"
echo $?

I get ‘0’ when ${testPath} is in ${PATH} and ‘1’ when it is not. I guess that is what you need.
$pathIncluded stays empty, that is caused by the grep parameter ‘-q’, which means, according to man grep:
“Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option.”

1 Like

I think I found the actual issue now. Thanks for the accidental help.

pathIncluded="$(echo "${PATH}" | grep -q "${testPath}")$?"

and

if [[ "$(echo "${PATH}" | grep -q "${testPath}")$?" == 0 ]]; then
  echo "Included."
else
  echo "Not included."
fi

now work for me. Seems like I forgot to call the return value instead of the literal value returned by grep.

Seems like I was fighting with this for so long just to find out that I missed to type 2 characters, after all.

1 Like