Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Bash / Shell Scripting (http://www.programmingforums.org/forum26.html)
-   -   if condition and grep (http://www.programmingforums.org/showthread.php?t=15879)

nuvox May 25th, 2008 7:39 AM

if condition and grep
 
hey all

im trying to write a script, need some help

concept goes like this: i want to grep a file for a word/phrase, and depending on grep's output (basically, any output at all = found, NULL = not found) to do -something-.

basically, in pseudocode:
:

if(grep_output == NULL):
    echo "not found";
else:
    echo "found"

could someone point me in the right direction? thanks in advance!

nuvox May 25th, 2008 9:29 AM

Re: if condition and grep
 
okay, figured it out.
:

grep_output=`grep <word> <file>`
if [ "$grep_output" == "" ]; then
    echo "not found";
else
    echo "found";
fi


Jessehk May 25th, 2008 9:38 AM

Re: if condition and grep
 
:

  1. #!/bin/bash
  2.  
  3. if grep "found" "example.sh" > /dev/null; then
  4.     echo "Found"
  5. else
  6.     echo "Not found"
  7. fi


gromit Sep 9th, 2008 1:23 AM

Re: if condition and grep
 
More streamlining! :)

:

#!/bin/bash
if grep -q "found" "example.sh" ; then
    echo "Found"
else
    echo "Not found"
fi


Or if you want to have the grep output in a variable to manipulate it later, here's a tidier version of your original example (your original example will work fine, some of us just like to tweak ;)

:

#!/bin/bash
if [ $# -ne 2 ] ; then
  echo "usage: $0 <word> <file>"
fi

grep_output="$(grep $1 $2)"

if [ -z "$grep_output" ]; then
    echo "not found";
else
    echo "found";
fi



All times are GMT -5. The time now is 10:10 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC