
09-14-2001
|
|
Goober Extraordinaire
|
|
|
Join Date: Jul 2001
Location: Portland, OR, USA
Posts: 1,584
|
|
I was just thinking about it, and I guess this isn't the most helpful was to explain this. I'm going to add some comments (in bold) to the code, so you can see what's happening step by step:
Quote:
Originally posted by LivinFree
Code:
#!/bin/sh
# check.sh
# This script takes two arguments -
# The first is the word you a looking for,
# and the second is the file you want to find
# the word in.
# Example: check.sh lamb haggis
# Will look for the word "lamb" in the file "haggis"
# This is to make sure there are exactly two arguments
# passed to the script. If not, it will give you a little hint...
# The "$#" counts the number of aguments, and -ne is the same
# as saying "not equal".
if [ "$#" -ne "2" ] ; then
echo "Usage: "
echo "`basename $0` {search string} {file} "
exit 2
fi
[/b]# Right here, we check to make sure the file we are searching
# exists, and is a regular file. For more information on the -f
# statement, use the 'man test' command.[/b]
if [ -f "$2" ] ; then
# We don't actually want to see the results of the search,
# we only want to know if it was successful, so we send the
# output to /dev/null - to nowhere-land
grep "$1" $2 > /dev/null
# The "$?" construct tells you the status of the last command.
# if $? is equal to zero, the command was successful, if it is any
# number other than 0, there was a problem
case $? in
0) echo -e "\nThe word \"$1\" was found in the \"$2\" file! \n" ;;
*) echo -e "\nThe word \"$1\" was NOT found in the \"$2\" file! \n" ;;
esac
exit 0
# This is what happens if the file did not exist (see above)
# This is our backup plan - it keeps grep from getting "stuck"
# if there is no file
else
echo "The \"$2\" file does not exist"
exit 2
fi
The exit 0 tells it to exit successfully (remember $?), and exit 2 tells it that there were errors, and to exit right away. I hope this is a little more helpful
This is one of many ways to do it...
|
By saying this is one of many, I mean it - here is an example of a one-liner that will do nearly the same thing without the error handling or variables:
Code:
grep lamb haggis > /dev/null && echo Word found in file || echo Word NOT found in file
As you can see, the "grep" command is the same as in the script, but the messages are handled differently. The commands after the "&&" will execute if the previous command was successful, and the command after the "||" will execute if it was not successful.
Geez, I'd make a horrible teacher...
Last edited by LivinFree; 09-14-2001 at 03:54 AM..
|