Using spaces in a bash pattern


Forum: Programming and Scripting
Topic: Using spaces in a bash pattern
started by: rlr0304

Posted by rlr0304 on Jan. 19 2007,10:40
I'm trying to examine the results of a ping to determine if there was a packet lost.  But, I'm having trouble getting a bash pattern to work when there is a space in the pattern.

This works:
  sResult=$(ping -c 1 192.168.0.120)
  if [[ $sResult == *packet* ]]
  then
      echo packet found
  else
      echo packet not found
  fi

But, if I try to search for "packet loss", I can't get it work.

Bash gives a syntax error if I use the statement:
  if [[ $sResult == *packet loss* ]]
and neither
  if [[ $sResult == "*packet loss*" ]]
or
  if [[ $sResult == '*packet loss*' ]]
works.

Neither does
  if [[ $sResult == *packet\sloss* ]]

I've also tried searching Google for bash pattern expressions and haven't found any helpful documentation.  No one seems to ever search a string that contains spaces.

And yes, I know I can pipe the result of pipe and use grep.  But, I'm trying to relearn bash scripting (it been an extremely long time) and I would like to get it work if possible.

Can someone help me out?

TIA,

Richard

Posted by mikshaw on Jan. 19 2007,13:48
Try this one:
if [[ $sResult == *packet\ loss* ]] (backslash followed by a literal space)
EDIT: that doesn't work =o(


Another option is case:
Code Sample
case $sResult in
*packet\ loss*) echo packet not found;;
*) echo packet found;;
esac

Posted by ^thehatsrule^ on Jan. 19 2007,13:51
Afaik you can use double quotes to signify a string (use them on both sides of the comparison) - this is one of the things I always do in scripting unless what I'm comparing are integers.  You could also use a case statement instead.

EDIT:
heh, just saw mikshaw's post.  I guess whichever way you choose depends on your style - I prefer not using the "\ " since it is somewhat harder to read (imo).

Posted by mikshaw on Jan. 19 2007,18:38
There's another possible issue, although at this time I can only say "possible" since I haven't done any testing.

I've never quite understood the use of double brackets when doing a single test. I've used them when doing multiple tests in the same line but that was it. Normally I'd do this:
if [ "$sResult" == "packet loss" ]; then

Note the double quotes in _both_ parts of the test. I think this is necessary when comparing strings that may potentially contain spaces.

HOWEVER....
Wildcards apparently don't work in tests like this. You might need to take a different approach.  You could use the case statement i mentioned before, or another option is grep, although it may be a little overkill....
if echo "$sResult" | grep -q "packet loss" ; then

The "-q" suppresses output from grep, since you are just testing its exit status.

Posted by rlr0304 on Jan. 23 2007,07:07
Thanks for the input guys.

Richard

Powered by Ikonboard 3.1.2a
Ikonboard © 2001 Jarvis Entertainment Group, Inc.