Below is the code I am trying:

echo "Enter dirname and hit Return"
read input1
echo "Enter a pattern to be searched for in the current directory"
read input2
find /*/${input1}/*/logs/*/*/*/* -name '*.gz' -exec sh -c 'gzip -cd "$0" | grep -- "${input2}"' {} \;

while the input1 matches but the input2 doesnt seem to match and I am getting all the outputs of input1 without getting input2 matched with it.

purpose is to read all the .gz files and get the keyword input2 match.

  • the only problem is while I try to run the above in script. If I try to run the command in bash, it works! find /*/input1/*/logs/*/*/*/* -name '*.gz' -exec sh -c 'gzip -cd "$0" | grep -- "input2"' {} \; it works when I dont go for variable.
    – learner
    Oct 25, 2017 at 14:04
  • Use bash -x to debug the script. Oct 25, 2017 at 14:08
  • 1
    Likely the single quotes around the find/exec are preventing expansion of input2
    – Jeff Schaller
    Oct 25, 2017 at 14:18
  • You need to export input2 for it to be available to sh. Also add -r to read for it not to treat backslash specially. Add IFS= for read not to strip leading and trailing blanks. (and quote $input1) Oct 25, 2017 at 14:20
  • Thanks for the response folks. I am a network(firewall/routing/switching) guy just trying my hand in scripting. Modifying the quotes isnt helping. Could you please type the last line of my code, which you want me to try.
    – learner
    Oct 25, 2017 at 14:38

1 Answer 1


The "internal" script that find calls does not have access to the $input2 variable.

You may instead do

find /*/"$input1"/*/logs/*/*/*/* -name '*.gz' \
    -exec sh -c 'gzip -cd "$1" | grep -e "$0"' "$input2" {} \;

This passes the value of $input2 into the internal script and will make it available as $0 while the filename argument will be $1.

Alternatively, just let find decompress the files and filter the output from find as a whole:

find /*/"$input1"/*/logs/*/*/*/* -name '*.gz' \
    -exec gzip -cd {} + | grep -e "$input2"

Since find already enters into all subdirectories of the given top-directory, you can probably leave out some of the filename globs and instead use -mindepth 4 (if your find supports this option), and add -type f to signal that you're only interested in regular files:

find /*/"$input1"/*/logs -mindepth 4 -type f -name '*.gz' \
    -exec gzip -cd {} + | grep -e "$input2"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .