LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   getting the status of grep (https://www.linuxquestions.org/questions/linux-newbie-8/getting-the-status-of-grep-681101/)

Acidg3rm5 11-04-2008 01:39 PM

getting the status of grep
 
hi, i have the following codes, which prompt my user to change the item's description.

I want to be able to tell user that no such item exist if the search returns nothing. How to i do it?

echo "Please enter the item description you wish to inquire"
read itemDesc
#use grep to search. -i to ignore case, -w to match the string.
grep -iw "$itemDesc" sales.txt
#need a if else statment here to get status of grep. echo "No such item #found if grep has no results"
echo "Press enter to return to main menu"

nishamathew1980 11-04-2008 02:05 PM

You will find all the scripting help you will need here - http://tldp.org/LDP/abs/html/

Enjoy!
:)

Linux Archive

jailbait 11-04-2008 02:21 PM

You need to check the return code from the grep command. You find the return code from the most recent command in the $? variable i.e.:

grep -iw "$itemDesc" sales.txt
if test "$?" != 0;
then

----------------------
Steve Stites

chrism01 11-04-2008 06:01 PM

I prefer the numeric test
Code:

if [[ $? -ne 0 ]]
then
    echo "not found"
fi


Acidg3rm5 11-05-2008 08:36 AM

Quote:

Originally Posted by chrism01 (Post 3331853)
I prefer the numeric test
Code:

if [[ $? -ne 0 ]]
then
    echo "not found"
fi


Thanks. it worked. Anyway, am trying to put a nice output after i search. but i'm hitting an error.

Code:

search=`grep -iw "$itemDate" sales.txt`

if [[ $? -ne 0 ]]
then
    echo "Item not found."

else

    echo $search | awk 'BEGIN{ FS=":" print "Description\t \Unit Price\t \tQty\t Date"} {printf("%s\t%s\t  $%.2f\n", NR,$4,total)}'
fi

I would actually want to display the items when found to something like this:

Description Unit Price Qty Date
Coke 1 20 01Nov08
Chocolate 3 100 01Nov08

Anyone can give me some clues what went wrong with my AWK?

Acidg3rm5 11-05-2008 10:38 AM

Thought that i should not start a new thread to ask for help. got another problem in my program
Quote:

cat -b sales.txt
echo "Please enter the number you wish to delete: "
read choice
sed -i "$choice d" sales.txt

#need a if statement here. if sed -i "$choice d" sales.txt is invalid, i want to print an error message that tells user he selected wrong #choice.

#else. it prints the below
echo "Transaction No. $choice deleted!"


echo "Press enter to return to main menu"
read
;;

chrism01 11-05-2008 06:14 PM

Define 'invalid' ?


All times are GMT -5. The time now is 09:38 PM.