Redirect grep output to file

I'm not sure why this redirect provided in the code does not work. Every time I run the script, the output file is always empty. Does anyone have an idea?

Thanks.

#!/bin/sh LOOK_FOR="DefaultProblem" FILES=`ls plugins/*source*.jar` for i in $FILES do # echo "Looking in $i ..." unzip -p $i | grep -i $LOOK_FOR > output #> /dev/null if [ $? == 0 ] then echo ">>>> Found $LOOK_FOR in $i <<<<" fi done 
+6
source share
4 answers

You can use >> (append) instead of > (rewrite) to redirect as:

 unzip -p $i | grep -i $LOOK_FOR >> output #> /dev/null 

Since you execute this command in a loop and overwrite the output file each time, it may be empty at the end if the most recent grep command does not find any corresponding line in the unzip output.

+9
source

You have three problems.

  • Do not try to parse ls output. Instead, just use for i in plugins/*source*.jar . The main reason is that your script will completely and completely break down on any files with spaces in their names. See this link for an explanation of why ls cannot be parsed.
  • You need to use >> instead of > , since the latter will overwrite the output file at each iteration of the loop. The first will be added to it.
  • Use more quotes! You want to specify your variables to make sure they are not subject to word splitting.

Alternatively, you can embed the if test. Therefore, combining all this, we have:

 #!/bin/sh LOOK_FOR="DefaultProblem" for i in plugins/*source*.jar do # echo "Looking in $i ..." if unzip -p "$i" | grep -i "$LOOK_FOR" >> output #> /dev/null then echo ">>>> Found $LOOK_FOR in $i <<<<" fi done 
+3
source

You can redirect the output of the entire loop:

 #!/bin/sh LOOK_FOR="DefaultProblem" FILES=`ls plugins/*source*.jar` for i in $FILES ; do # echo "Looking in $i ..." 1>&2 unzip -p $i | grep -i $LOOK_FOR if [ $? == 0 ] ; then echo ">>>> Found $LOOK_FOR in $i <<<<" 1>&2 fi done > output 

Please note that I redirected diagnostic messages to stderr.

+2
source

Instead of for loop and if conditional you can do everything in one find

 find /path/to/plugins -name "*source*.jar" -exec sh -c 'unzip -l "{}" | grep -q DefaultProblem' \; -print 
0
source

Source: https://habr.com/ru/post/906072/


All Articles