unixgreplogfilelog-files

Unix: Unexpected behavior of grep command with regex search


I have a grep command that I run daily to find an entry in a huge logfile.

This command works fine in our Development environment. But in our Production environment, it outputs a response that is different from the entry in the logfile.

Here's the command:

logentry=$(grep -m1 -oP '.*(?<=Reset\s).*' $log)

Actual entry in log file:

******Reset  Counter:[Total:1849766] [Success:1849766]  [Insert:102]  [Update:1848861]  [Delete:803]  [Key:0]

Command output:

******Reset  Counter:[Total:1849766] 1  [Insert:102]  [Update:1848861]  [Delete:803]  [Key:0]

Expected output:

 ******Reset  Counter:[Total:1849766] [Success:1849766]  [Insert:102]  [Update:1848861]  [Delete:803]  [Key:0]

What could be the reason behind this inconsistent behavior of the grep command?


Solution

  • Thanks @Ed Morton for comment. The fix is working fine.
    Root cause: The variable is not quoted so it's open to globbing, word-splitting, and filename expansion and so the net result will be dependent on files in your directory.

    Solution: Use echo "$logentry" instead and ALWAYS quote your shell variabes unless you have a specific purpose in mind by not doing so and fully understand all of the implications.

    Security implications of forgetting to quote a variable in bash/POSIX shells