Search code examples
linuxbashgrep

BASH: can grep on command line, but not in script


Did this million times already, but this time it's not working I try to grep "$TITLE" from a file. on command line it's working, "$TITLE" variable is not empty, but when i run the script it finds nothing

*title contains more than one word

echo "$TITLE"
cat PAGE.$TEMP.2 | grep "$TITLE"

what i've tried:

echo "cat PAGE.$TEMP.2 | grep $TITLE"

to see if title is not empty and file name is actually there


Solution

  • Are you sure that $TITLE does not have leading or trailing whitespace which is not in the file? Your fix with the string would strip out whitespace before execution, so it would not see it.

    For example, with a file containing 'Line one':

    /home/user1> TITLE=' one '
    /home/user1> grep "$TITLE" text.txt
    /home/user1> cat text.txt | grep $TITLE
    Line one
    

    Try echo "<$TITLE>", or echo "$TITLE"|od -xc which sould enable you to spot errant chars.