operators in if loop

Hi all,

I have a variable which is having the value like below,

$ echo ${p}
8 15 22 30
$

My requirement is that the variable should return true when it contains only one number like below,

$ echo ${p}
15
$

Otherwise, it should return false if it contains more than one number.
I tried to find out the if loop operator which helps in this, but could not find anything.
Could anyone help me in this please?

Regards,
Raghu

Which shell and O/S are you using?

Generally this should work.

if echo $p | grep -E '[ ]+'; then
 echo return true 
else 
 echo return false 
fi

Here, I am matching whether the variable contains "spaces".

If you have modern bash, You could directly use regular expressions inside an "if" statement.

Only test for whole positive numbers

case $p in
  *[^0-9]*) echo false;;
  *)        echo true;;
esac

--
General test for number of fields:

This should work for spaces tabs and newlines:

if ( set -- $p; [ $# -eq 1 ] ); then
  echo true 
else 
  echo false 
fi

or

singlefield(){
  [ $# -eq 1 ]
}

if singlefield $p; then
  echo true
else
  echo false
fi

These should work for spaces only as a field separator

if [ "$p" = "${p% *}" ]; then 
 echo true 
else 
 echo false 
fi
case $p in
  *\ *) echo false;;
  *)    echo true;;
esac

If you'd like a reasonably bullet-proof solution, specify the exact forms that the numeric representation is allowed to assume.

Because we have no context, it's possible that the best solution lies in an earlier step, when or before the variable is assigned.

In my opinion, Scrutinizer's first suggestion is best. It doesn't require any external utilities, so it's efficient. It is also trivially extensible, for handling multiple representations.

I wouldn't recommend the following for production use. It's more an exercise in utility abuse than anything else ;):

expr "$p" >/dev/null 2>&1

Regards,
Alister

Thanks everybody...

All are very helpful examples.... But i'm gonna use Scrutinizer's second example as it is bit extendable for me in my requirement.

Thanks again for all your valuable inputs.

Regards,
Raghu