A log may involve connection errors, timeouts, and health checks. To identify multiple symptoms without confusing literal text and regular expression, start with grep -F and add an -e for each search string. The patterns will be linked by an OR: a line matching one of them will be retained.
If you are new to the command, first consult the basics of the grep command in Linux. Here, the goal is different: to compose a reusable filter, separate inclusions from exclusions, and control what the result means.
Searching multiple strings with -F and -e
-F tells GNU grep to treat each pattern as a fixed string. -e introduces a pattern; it does not itself disable the interpretation of special characters. Add as many -e as necessary:
# Retain lines containing ERROR or WARN; -n displays their number in the file.
grep -nF -e 'ERROR' -e 'WARN' -- application.log
The expected result is one line retained per line, even if it contains both patterns. In the synthetic fixture presented below, this command returns five lines. The line “ERROR WARN multiple failures” is not duplicated: grep selects lines, not an occurrence per pattern.
The separator -- marks the end of options and the start of the path. For a pattern that begins with a dash, use -e so it is not taken for an option:
# Both patterns are literals, including the initial dash of the second.
grep -nF -e '192.0.2.10' -e '-ERROR' -- application.log
The apostrophes around the patterns are ASCII apostrophes, typed from the keyboard. They prevent the shell from interpreting their content. Do not use typographic quotes copied from a word processor.
With -F, the dots in 192.0.2.10 are literal dots. Add -i only if case really varies in the data: this makes the search case insensitive. Fixed strings are suitable for exact messages, addresses, and identifiers.
Using -E when variants are regular expressions
Choose -E when you need variants expressed by a regex. The character | means “or”:
# Same intent as -F with two simple words: ERROR or WARN.
grep -nE -e 'ERROR|WARN' -- application.log
# Stricter variant: level at the beginning of the line, followed by a space or the end.
grep -nE -e '^(ERROR|WARN)([[:space:]]|$)' -- application.log
The first command finds the terms wherever they appear in a line. The second requires a level at the beginning of the line. Use it only if the actual format guarantees it: a timestamped log may start with the date, not with ERROR or WARN.
The modes -F and -E are alternative: do not combine them. With -F, ERROR|WARN refers to the string containing the vertical bar character; it is not an alternation. Similarly, in a regex, the dot in 192.0.2.10 matches any character. To search for this address exactly, keep -F.
Loading a list of patterns with -f
When symptoms recur often, place them in a rules file: -f reads one pattern per line. Prepare the files in a new private directory, never in place of a log or in /etc. TMPDIR must point to an existing and trusted directory; otherwise, the command falls back to your home directory.
# Create a new working directory and navigate to it; abort on failure.
workshop=$(mktemp -d "${TMPDIR:-$HOME}/grep-patterns.XXXXXX") || exit 1
cd -- "$workshop" || exit 1
# A literal pattern per line in each file.
printf '%sn' 'ERROR' 'WARN' > patterns.txt
printf '%sn' 'healthcheck' > exclusions.txt
Then create a clearly synthetic demonstration fixture. It serves to illustrate the behavior of commands; it is not an export of Nginx logs nor the result of an intervention on a real server.
# Create a small local test set in the workshop directory.
printf '%sn'
'INFO starting'
'ERROR connection refused 192.0.2.10'
'WARN timeout'
'ERROR healthcheck timeout'
'ERROR WARN multiple failures'
'INFO 192x0x2x10'
'-ERROR pattern with dash' > application.log
To search for the fixed strings in patterns.txt:
# Each line of patterns.txt is a distinct fixed pattern.
grep -nF -f patterns.txt -- application.log
For a list of regex, replace -F with -E and write each rule as a regular expression. Text such as # comment is not a special comment: grep will search for it literally. Multiple -e options, multiple -f files, or their combination add patterns to the search. They do not create an AND condition.
Checking rules before launching the filter
A completely empty pattern file contains no rules: no lines are retained. In contrast, an empty line in the file is a blank pattern, which may match all lines. Check the file before relying on a result:
# Check that the file contains bytes.
test -s patterns.txt
# Report any empty line; also check grep's status.
if grep -n -e '^$' -- patterns.txt; then
printf '%sn' 'Warning: empty pattern in the rules file.'
fi
# Display characters, including any potential CRLF line endings.
od -c patterns.txt
test -s checks that the file is not empty but does not guarantee that its rules are relevant. Checking with grep detects an empty line; a read error must also be taken into account. With od -c, check if the line endings contain a carriage return r, a possible sign of a CRLF file. Do not blindly normalize the file: first identify its format and origin.
Combining symptoms and then removing noise with -v
To keep lines containing ERROR or WARN and then exclude those containing healthcheck, apply the two steps successively:
# Inclusion: ERROR or WARN. Exclusion: then remove healthcheck lines.
grep -F -f patterns.txt -- application.log | grep -vF -f exclusions.txt
The first list defines the patterns to include; the second, independent, defines the noise to exclude. Do not add the exclusion file as a second -f to the first grep: you would add healthcheck to the search patterns and thus retain those lines. Here, four lines remain in the synthetic fixture.
-v reverses the global selection. With multiple exclusion patterns A and B, grep -vF -e 'A' -e 'B' retains lines that contain neither A nor B. It does not mean “not A or not B.” Keep this usage brief: if your goal is to produce a new copy without modifying the original, rather follow the method to exclude lines without modifying the source file.
An AND between two strings on the same line is achieved with two successive filters:
# Keep lines containing ERROR, then among them those containing WARN.
grep -F -e 'ERROR' -- application.log | grep -F -e 'WARN'
The two words may appear in any order. A line must pass both steps to remain. In the fixture, only “ERROR WARN multiple failures” is retained. This process applies to lines: do not apply it to context blocks produced with -C assuming their relationships will be preserved. After a pipeline, a number added by the last grep -n would count the lines of the intermediate stream, not necessarily their original number in the log.
Applying the filter to the real log of the right service
Before searching in a file, check its path and your reading permissions. The Nginx example below is only valid if this file exists on your machine; the fragments are illustrative and should be replaced with messages observed in the relevant log.
# Check the readability of the path before searching.
test -r /var/log/nginx/error.log
# Example of literal search; adapt the fragments to the actual log.
grep -nF -e 'upstream timed out' -e 'connect() failed' -- /var/log/nginx/error.log
If test -r fails, check the path, the service, and the access rights expected for your account. Do not launch a global recursive search and do not modify the log permissions to work around the issue. A path under /var/log is not universal.
On a machine using systemd, you can limit reading to a unit, the current boot, and a time window. Check that the unit exists and adjust the period to the incident; consult journalctl --help on the target if its options differ.
# Check the status of the unit without opening a pager.
systemctl status nginx.service --no-pager
# Read the journal of the unit since the current boot, over the last 30 minutes.
journalctl -u nginx.service -b --since '30 minutes ago' --no-pager -o short-iso
# Filter the text output by journalctl; this is not a structured query on its fields.
journalctl -u nginx.service -b --since '30 minutes ago' --no-pager -o short-iso |
grep -iF -e 'timed out' -e 'failed'
A non-zero status from systemctl status may indicate that the unit is inactive; it does not prove by itself that the command is malformed. An empty or incomplete log may also reflect reading permissions. To return to the original line and its context, see how to find an error in logs with its context.
These commands are examples to adapt: no real Nginx server has been queried for this article. Before sharing an excerpt, check the time and unit, anonymize IP addresses, usernames, and tokens, and do not publish a private log.
Checking the result and diagnosing an empty filter
On the fixture, the forms -F -e, -E for these simple words and -F -f select the same five lines. You can also count the selected lines:
# Count lines containing at least one pattern, not total occurrences.
grep -cF -e 'ERROR' -e 'WARN' -- application.log
The expected result is 5: the line containing both strings counts only once. After excluding healthcheck, four lines remain; with the AND between ERROR and WARN, one remains.
GNU grep normally returns code 0 if at least one line is selected, 1 if none are, and 2 in case of an error. A valid search without matches is thus not the same as a command failure. Capture the status without !, which would invert its meaning:
# Explicitly retain the exit code of grep, including absence of matches.
rc=0
if grep -F -f patterns.txt -- application.log; then
rc=0
else
rc=$?
fi
printf 'Grep code: %sn' "$rc"
In a Bash pipeline, the ordinary status of the command is that of the last stage. To control both filters, immediately copy PIPESTATUS: no command should interpose between the pipeline and this capture.
# Execute inclusion then exclusion, and immediately capture both statuses.
grep -F -f patterns.txt -- application.log | grep -vF -f exclusions.txt
codes=("${PIPESTATUS[@]}")
printf 'Inclusion: %s; exclusion: %sn' "${codes[0]}" "${codes[1]}"
A status of 1 at a stage may simply indicate that no line passed this filter; a status of 2 indicates a GNU grep error to examine. The only final status does not prove that the first stage read its source correctly. This capture is intended for interactive Bash: if your script uses set -e, manage expected codes explicitly before transitioning control there.
Avoid -q to certify that all input has been read: in quiet mode, grep can return 0 as soon as it finds a match, even if an error occurs afterward. To understand an empty or overly broad result, check in this order: the path and permissions, case, presence of an anchor incompatible with the format, choice between literal and regex, empty lines and CRLF endings, then the scope of exclusions. Multiline events, compressed archives, structured JSON data, and binary files require a different method.
Sources and behavior of commands
The matching rules and return codes described here are based on the Debian bookworm grep(1) man page. The options for reading the systemd journal are documented in the official journalctl documentation.
The outputs mentioned in the article concern only the synthetic fixture described above. The core filtering commands have been verified on this with GNU grep 3.11; the Nginx preflight examples and reading with journalctl are not presented as having been executed on a server.