Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old May 25th, 2008, 8:39 AM   #1
nuvox
Newbie
 
Join Date: May 2008
Posts: 2
Rep Power: 0 nuvox is on a distinguished road
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 is offline   Reply With Quote
Old May 25th, 2008, 10:29 AM   #2
nuvox
Newbie
 
Join Date: May 2008
Posts: 2
Rep Power: 0 nuvox is on a distinguished road
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
nuvox is offline   Reply With Quote
Old May 25th, 2008, 10:38 AM   #3
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 661
Rep Power: 10 Jessehk is on a distinguished road
Re: if condition and grep

bash Syntax (Toggle Plain Text)
  1. #!/bin/bash
  2.  
  3. if grep "found" "example.sh" > /dev/null; then
  4. echo "Found"
  5. else
  6. echo "Not found"
  7. fi
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Old Sep 9th, 2008, 2:23 AM   #4
gromit
Newbie
 
Join Date: Sep 2008
Posts: 1
Rep Power: 0 gromit is on a distinguished road
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
gromit is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 1:27 AM.

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