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

Re: bash: problem with [sets]



On Mon, 23 Jun 2003 23:48:10 +0100
Colin Watson <cjwatson@debian.org> wrote:

> On Mon, Jun 23, 2003 at 03:37:43PM -0500, matt zagrabelny wrote:
> > On Mon, 2003-06-23 at 13:57, David selby wrote:
> > > If this is the case, how can I test a string ?
> > 
> > for your enjoyment:
> > 
> > #!/bin/bash
> >  
> > if echo $fourdig | grep ^[0-9]*$ > /dev/null 2>&1; then
> 
> That *really* needs some quoting ...
> 
>   if echo "$fourdig" | grep '^[0-9]*$' > /dev/null 2>&1; then

Yes, and you can add a -q to the grep invocation and remove the
redirections:

	if echo "$fourdig" | grep -q '^[0-9]*$'; then

but this still requires an extra fork/exec to launch the grep.

So in the spirit of Internet Over-answering here are two more ways to
answer the question (which don't fork).

If you want to use shell globbing, another trick you can try to just the
case statement.  An example:

	case "$fourdig" in
		[0-9][0-9][0-9]) echo "three digits";;
		[0-9][0-9][0-9][0-9]) echo "four digits";;
		a*) echo "starts with a";;
		*) echo "dunno";;
	esac

This should work in old Bourne shell (say, like /bin/sh on Solaris).

Another way is:

	if [ -z "${fourdig#[0-9][0-9][0-9][0-9]}" ]; then ...

(remove the left most pattern of four digits and test the resulting
string length against zero)

This requires bash (or at least a ksh).

Both of the above suggestions will not fork a separate process (which
is useful if you care about performance but not enough to code in C).

Arcane?  You betcha.

-g

Attachment: pgpUGG0XkxAMG.pgp
Description: PGP signature


Reply to: