help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Help With School Assignment, Learning Bash Scripts


From: Greg Wooledge
Subject: Re: [Help-bash] Help With School Assignment, Learning Bash Scripts
Date: Thu, 6 Nov 2014 08:22:23 -0500
User-agent: Mutt/1.4.2.3i

On Wed, Nov 05, 2014 at 07:54:58PM -0800, Jesse Molina wrote:
> The second difficult part of your task above is the "If the grep is 
> successful" part.  What does that mean? How are you going to test if 
> grep is successful or not successful in finding that pattern?  There are 
> actually multiple ways of doing this with bash.  This one might be 
> tricky for a noob and you should ask your teacher for help on this one 
> if you don't already know what to do.

Since I'm not a fan of the Socratic method of "teaching", I'll just state
the correct answer to this.  You test the exit status of grep by using an
"if".  You also silence grep by using the -q option, because you don't
care about its output -- just its exit status.

if printf '%s\n' "$number" | grep -q 'some regular expression'; then
  echo "invalid input '$number'"
  exit 1
fi

The exit status of a pipeline is that of the last command in the pipeline
(in this case, grep).  The "if" keyword takes a list of arbitrary commands.
Any commands at all.  They don't have to be [ or [[ commands.  They can
be pipelines ending in grep.

Now, an experienced bash programmer would not use grep here at all.
(S)he would use shell builtin pattern matching (either case or [[)
to test the variable's contents *directly* without forking an external
command like grep.  But this was addressed in previous messages.

> The reason I say that is because 
> they might have recently taught you this and they expect it to be done 
> in a certain way. They are going to know you cheated yourself if you use 
> one of the other many methods.

"Cheated" himself, or taught himself?  Where does one draw the line?



reply via email to

[Prev in Thread] Current Thread [Next in Thread]