Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

shell script

Status
Not open for further replies.

munderw2

MIS
Joined
Sep 30, 2008
Messages
1
Location
US
I'm writing a script in solaris 9, and need to test the standard out of a grep operation to see if it finds anything. Any ideas? Here's the code i have:

onstat -u|grep "Y--P"|awk '{print $1,$2,$3}'

I want to put it in an if statement like this:
If
grep returns something
then
else
exit
fi


 
The $? is the return code from the previous run cmd. Return of 0 is good (it found something) return of higher is bad (nothing found).

Code:
onstat -u |grep "Y--P" >/dev/null 2>&1

if [[ $? -lt 1 ]]
then
    echo "Found Needle"
else
    echo "Haystack Clean"
fi
OR this would probably be more useful
Code:
needle=`onstat -u |grep "Y--P"` 2>/dev/null
if [[ $? -lt 1 ]]
then
    echo "Found Needle:"
    echo ${needle}
else
    echo "Haystack Clean"
fi

 
Typically, based on Ed's first example, I would do it like this:

Code:
if onstat -u |grep "Y--P" >/dev/null 2>&1
then
    echo "Found Needle"
else
    echo "Haystack Clean"
fi

But because of the awk step in there, I'd adapt Ed's second example as follows:

Code:
needle=`onstat -u |grep "Y--P"` 2>/dev/null
if [[ $? -lt 1 ]]
then
    echo "Found Needle:"
    echo ${needle} | awk '{print $1,$2,$3}'
else
    echo "Haystack Clean"
fi

But... again... if it were me, I probably wouldn't use grep at all:

Code:
needle=$(onstat -u | awk '/Y--P/ {print $1,$2,$3}')
if [[ "$needle" ]]
then
    echo "Found Needle:"
    echo ${needle} 
else
    echo "Haystack Clean"
fi

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top