Shell – grep: Not a recognized flag in AIX

aixgrepshell-script

I am trying to write a shell which will fetch a set of data from table and write it to a text file whose name is result.txt . Now I will pick each line from this file and search it in a log file and check if it present or not. If it is not found in the log file I want to write it in a separate file say notfound.txt. I am working on a AIX server and getting this below error for the grep command. Can somebody please help me figure out what's wrong?

Here is my script,

while read -r LINE; do
    grep -q "$LINE" log.log 
    if [  $? -eq 0 ]
    then
       echo "$LINE" >> /home/notfound.txt
    fi
done  < result.txt

which gives me following output,

grep: Not a recognized flag: –
Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] -e pattern_list…
[-f pattern_file…] [file…]

Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] [-e pattern_list…]
-f pattern_file… [file…]

Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] pattern_list [file…]

Best Answer

Looks like $LINE contains a value which starts with a dash.

You can protect against this with

grep -q -e "$LINE"

More generally, most Unix commands allow -- to mark the end of options, and so any argument after this "end of options" option will be taken as a literal, non-option argument.

echo will have a problem, too; the portable solution is to switch to printf, which works fine with arguments which start with dashes, as long as it's not the first argument, which is a format string.

You should also avoid using uppercase variable names; these are reserved for system use.

Finally, scripts should almost never need to explicitly examine $? - this is already done by if, while and other control constructs.

if grep -q -e "$line" log.log; then
    printf '%s\n' "$line"
fi

As an optimization, placing the redirection outside the loop will make things a lot quicker.

while read -r line; do
    grep -q -e "$line" log.log && printf '%s\n' "$line"
done <results.txt >notfound.txt
Related Question