3 # xzgrep -- a wrapper around a grep program that decompresses files as needed
4 # Adapted from a version sent by Charles Levert <charles@comm.polymtl.ca>
6 # Copyright (C) 1998, 2001, 2002, 2006, 2007 Free Software Foundation
7 # Copyright (C) 1993 Jean-loup Gailly
9 # Modified for XZ Utils by Andrew Dudman and Lasse Collin.
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 @enable_path_for_scripts@
22 #SET_PATH - This line is a placeholder to ease patching this script.
24 # Instead of unsetting XZ_OPT, just make sure that xz will use file format
25 # autodetection. This way memory usage limit and thread limit can be
26 # specified via XZ_OPT. With gzip, bzip2, and lzop it's OK to just unset the
27 # environment variables.
28 xz='@xz@ --format=auto'
29 unset GZIP BZIP BZIP2 LZOP
32 *egrep*) prog=xzegrep; grep=${GREP:-grep -E};;
33 *fgrep*) prog=xzfgrep; grep=${GREP:-grep -F};;
34 *) prog=xzgrep; grep=${GREP:-grep};;
37 version="$prog (@PACKAGE_NAME@) @VERSION@"
39 usage="Usage: ${0##*/} [OPTION]... [-e] PATTERN [FILE]...
40 Look for instances of PATTERN in the input FILEs, using their
41 uncompressed contents if they are compressed.
43 OPTIONs are the same as for '$grep'.
45 Report bugs to <@PACKAGE_BUGREPORT@>."
47 # sed script to escape all ' for the shell, and then (to handle trailing
48 # newlines correctly) turn trailing X on last line into '.
50 s/'\''/'\''\\'\'''\''/g
56 files_without_matches=0
60 # See if -H and --label options are supported (GNU and *BSDs).
61 if test f:x = "$(eval "echo x | $grep -H --label=f x 2> /dev/null")"; then
67 while test $# -ne 0; do
73 (-[0123456789abcdEFGhHiIKlLnoPqrRsTuUvVwxyzZ]*[!0123456789]*)
74 # Something like -Fiv was specified, that is, $option contains more
75 # than one option of which the first option (in this example -F)
76 # doesn't take an argument. Split the first option into a standalone
77 # argument and continue parsing the rest of the options (in this example,
78 # replace -Fiv with -iv in the argument list and set option=-F).
80 # If there are digits [0-9] they are treated as if they were a single
81 # option character because this syntax is an alias for -C for GNU grep.
82 # For example, "grep -25F" is equivalent to "grep -C25 -F". If only
83 # digits are specified like "grep -25" we don't get here because the
84 # above pattern in the case-statement doesn't match such strings.
85 arg2=-\'$(LC_ALL=C expr "X${option}X" : 'X-.[0-9]*\(.*\)' |
86 LC_ALL=C sed "$escape")
87 eval "set -- $arg2 "'${1+"$@"}'
88 option=$(LC_ALL=C expr "X$option" : 'X\(-.[0-9]*\)');;
89 (--binary-*=* | --[lm]a*=* | --reg*=*)
90 # These options require an argument and an argument has been provided
91 # with the --foo=argument syntax. All is good.
93 (-[ABCDefmX] | --binary-* | --file | --[lm]a* | --reg*)
94 # These options require an argument which should now be in $1.
95 # If it isn't, display an error and exit.
96 case ${1?"$option option requires an argument"} in
98 optarg=" '"$(printf '%sX\n' "$1" | LC_ALL=C sed "$escape");;
110 operands="$operands '"$(printf '%sX\n' "$option" |
111 LC_ALL=C sed "$escape");;
113 operands="$operands '$option'";;
115 ${POSIXLY_CORRECT+break}
120 (-[drRzZ] | --di* | --exc* | --inc* | --rec* | --nu*)
121 printf >&2 '%s: %s: Option not supported\n' "$0" "$option"
123 (-[ef]* | --file | --file=* | --reg*)
125 (--h | --he | --hel | --help)
126 printf '%s\n' "$usage" || exit 2
128 (-H | --wi | --wit | --with | --with- | --with-f | --with-fi \
129 | --with-fil | --with-file | --with-filen | --with-filena | --with-filenam \
133 (-l | --files-with-*)
136 (-L | --files-witho*)
137 files_without_matches=1
141 (-V | --v | --ve | --ver | --vers | --versi | --versio | --version)
142 printf '%s\n' "$version" || exit 2
148 option=\'$(printf '%sX\n' "$option" | LC_ALL=C sed "$escape");;
153 grep="$grep $option$optarg"
156 eval "set -- $operands "'${1+"$@"}'
158 if test $have_pat -eq 0; then
159 case ${1?"Missing pattern; try \`${0##*/} --help' for help"} in
161 grep="$grep -e '"$(printf '%sX\n' "$1" | LC_ALL=C sed "$escape");;
163 grep="$grep -e '$1'";;
168 if test $# -eq 0; then
174 # res=1 means that no file matched yet
179 *[-.][zZ] | *_z | *[-.]gz | *.t[ag]z) uncompress="gzip -cdf";;
180 *[-.]bz2 | *[-.]tbz | *.tbz2) uncompress="bzip2 -cdf";;
181 *[-.]lzo | *[-.]tzo) uncompress="lzop -cdf";;
182 *[-.]zst | *[-.]tzst) uncompress="zstd -cdfq";; # zstd needs -q.
183 *) uncompress="$xz -cdfqQ";; # -qQ to ignore warnings like unsupp. check.
185 # xz_status will hold the decompressor's exit status.
186 # Exit status of grep (and in rare cases, printf or sed) is
187 # available as the exit status of this assignment command.
190 ($uncompress -- "$i" 5>&-; echo $? >&5) 3>&- |
191 if test $files_with_matches -eq 1; then
192 eval "$grep -q" && { printf '%s\n' "$i" || exit 2; }
193 elif test $files_without_matches -eq 1; then
196 if test $r -eq 1; then
197 printf '%s\n' "$i" || r=2
201 elif test $with_filename -eq 0 &&
202 { test $# -eq 1 || test $no_filename -eq 1; }; then
204 elif test $grep_supports_label -eq 1; then
205 # The grep implementation in use allows us to specify the filename
206 # that grep will prefix to the output lines. This is faster and
207 # less prone to security bugs than the fallback method that uses sed.
208 # This also avoids confusing output with GNU grep >= 3.5 (2020-09-27)
209 # which prints "binary file matches" to stderr instead of stdout.
211 # If reading from stdin, let grep use whatever name it prefers for
212 # stdin. With GNU grep it is a locale-specific translated string.
213 if test "x$i" = "x-"; then
216 eval "$grep -H --label \"\$i\""
219 # Append a colon so that the last character will never be a newline
220 # which would otherwise get lost in shell command substitution.
223 # Escape & \ | and newlines only if such characters are present
224 # (speed optimization).
227 '* | *'&'* | *'\'* | *'|'*)
228 # If sed fails, set i to a known safe string to ensure that
229 # failing sed did not create a half-escaped dangerous string.
230 i=$(printf '%s\n' "$i" | LC_ALL=C sed 's/[&\|]/\\&/g; $!s/$/\\/') ||
231 i='(unknown filename):';;
234 # $i already ends with a colon so do not add it here.
237 # If grep or sed fails, pick the larger value of the two exit statuses.
238 # If sed fails, use at least 2 since we use >= 2 to indicate errors.
241 (eval "$grep" 4>&-; echo $? >&4) 3>&- |
242 LC_ALL=C sed "$sed_script" >&3 4>&-
245 test "$sed_status" -lt 2 && sed_status=2
246 test "$r" -lt "$sed_status" && r=$sed_status
253 # If grep or sed or other non-decompression command failed with a signal,
254 # exit immediately and ignore the possible remaining files.
256 # NOTE: Instead of 128 + signal_number, some shells use
257 # 256 + signal_number (ksh) or 384 + signal_number (yash).
258 # This is fine for us since their "exit" and "kill -l" commands take
259 # this into account. (At least the versions I tried do but there is
260 # a report of an old ksh variant whose "exit" truncates the exit status
261 # to 8 bits without any special handling for values indicating a signal.)
262 test "$r" -ge 128 && exit "$r"
264 if test -z "$xz_status"; then
265 # Something unusual happened, for example, we got a signal and
266 # the exit status of the decompressor was never echoed and thus
267 # $xz_status is empty. Exit immediately and ignore the possible
270 elif test "$xz_status" -ge 128; then
271 # The decompressor died due to a signal. SIGPIPE is ignored since it can
272 # occur if grep exits before the whole file has been decompressed (grep -q
273 # can do that). If the decompressor died with some other signal, exit
274 # immediately and ignore the possible remaining files.
275 test "$(kill -l "$xz_status" 2> /dev/null)" != "PIPE" && exit "$xz_status"
276 elif test "$xz_status" -gt 0; then
277 # Decompression failed but we will continue with the remaining
278 # files anwyway. Set exit status to at least 2 to indicate an error.
279 test "$r" -lt 2 && r=2
282 # Since res=1 is the initial value, we only need to care about
283 # matches (r == 0) and errors (r >= 2) here; r == 1 can be ignored.
284 if test "$r" -ge 2; then
285 # An error occurred in decompressor, grep, or some other command. Update
286 # res unless a larger error code has been seen with an earlier file.
287 test "$res" -lt "$r" && res=$r
288 elif test "$r" -eq 0; then
289 # grep found a match and no errors occurred. Update res if no errors have
290 # occurred with earlier files.
291 test "$res" -eq 1 && res=0
295 # 0: At least one file matched and no errors occurred.
296 # 1: No matches were found and no errors occurred.
297 # >=2: Error. It's unknown if matches were found.