I simply want to confirm that a path exists in another path using string variables.

My script:



# first try
#grep -q "$NEEDLE" "$HAYSTACK"

#second try
grep -q "${NEEDLE}" "${HAYSTACK}"

if [ $? -eq 0 ] ; then
    echo  "Your string has been found"
    echo "Your string has not been found"


me@localhost ~]$ ./testbash
grep: : No such file or directory
Your string has not been found

I suspect that because these are paths, I need to do a little more.

  • $HAYSTACK is empty. – Ipor Sircer Dec 21 '16 at 20:55
  • Updated my script... DEPLOY_PATH became HAYSTACK. I get the same error (with HAYSTACK not being found). It should only be evaluated as strings, not as actual paths. – TekiusFanatikus Dec 21 '16 at 20:57

Grep is expecting the command in the format grep [options] PATTERN [FILE...] so treats the second string as a file to scan through. If it's just the one line, you can send it it on stdin.

echo $haystack | grep $needle

Or however you'd prefer. Maybe with a here string:

grep $needle <<< $haystack

Bash has built-in pattern matching with the == comparison operator when using the [[ ]] form, so you could do something like this to avoid calling grep altogether:

if [[ $HAYSTACK == *${NEEDLE}* ]] ; then
    echo "Your string has been found"
    echo "Your string has not been found"

If you need to perform a more complex match, Bash also supports regular expression matching with the =~ operator.

  • What about if I wanted to test for a string directly without the NEEDLE variable? == "/path/here" ? – TekiusFanatikus Dec 22 '16 at 3:11
  • You can replace *${NEEDLE}* with whatever you want to compare against. If you enclose it with quotes, it will be taken as a literal string; without quotes (as in the example above), it will be treated as a pattern and wildcards * and ? will be expanded if present. Variable expansion follows the usual rules. – James Sneeringer Dec 22 '16 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.