Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect grep output to file

Tags:

bash

shell

sh

I am not sure as to why that redirection provided in the code does not work. Every time I run the script, the output file is always empty. Does anyone have an idea on that?

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
like image 287
fabricemarcelin Avatar asked Jan 16 '12 05:01

fabricemarcelin


3 Answers

You may want to use >> (append) instead of > (overwrite) for redirection as:

unzip -p $i | grep -iF "$LOOK_FOR" >> output

Since you're executing this command in a loop and overwriting file output every time, it might be blank in the end if very last command with grep doesn't find any matching line in unzip output.

like image 181
anubhava Avatar answered Oct 19 '22 22:10

anubhava


You have three problems

  1. Don't try to parse the output of ls. Instead just use for i in plugins/*source*.jar The major reason is that your script will completely and utterly break on any files that have spaces in their names. See this link for a litany of reasons why not to parse ls
  2. You need to use >> instead of > as the latter will overwrite the output file on each iteration of the loop. The former will append to it
  3. Use more quotes! You'll want to quote your variables to make sure they aren't subjected to word splitting

Also, you can inline the if test. So putting it all together 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
like image 23
SiegeX Avatar answered Oct 19 '22 20:10

SiegeX


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

Note that I've redirected the diagnostic messages to stderr.

like image 2
Keith Thompson Avatar answered Oct 19 '22 21:10

Keith Thompson