[Top][All Lists]

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

Re: [Help-bash] How to understand the end part

From: Eric Blake
Subject: Re: [Help-bash] How to understand the end part
Date: Mon, 02 Jan 2012 07:42:18 -0700
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:9.0) Gecko/20111222 Thunderbird/9.0

On 01/02/2012 07:32 AM, lina wrote:
> Hi,
> $ stringZ=abc123; echo `expr "$stringZ" : '.*' `

Your use of "echo `command`" is wasteful; almost anywhere you ever see
that pattern, you can be more efficient by just executing the command
directly (the only benefit from echoing the output of a command
substitution is whitespace normalization, as well as file name splitting
if the output happens to include glob characters since you didn't
enclose your `` in ""):

stringZ=abc123; expr "$stringZ" : '.*'

> I don't know how to understand the : '.*' part,
> Thanks for any explaination,

info expr

Or read the POSIX specification:

In expr, the ':' operator says to locate a match within the first string
according to the regular expression of the second string; with no
sub-expressions, the result is the number of characters that matched.
And since .* matches everything, that is a common idiom for  using expr
to compute the length of a string.

As long as you are okay assuming POSIX, your above expression is done
more efficiently without using 'expr' in the first place, as:

stringZ=abc123; echo ${#stringZ}

But if you care about portability to old shells like Solaris /bin/sh,
which lack the support for POSIX ${#var}, then expr is the portable

Eric Blake   address@hidden    +1-919-301-3266
Libvirt virtualization library

Attachment: signature.asc
Description: OpenPGP digital signature

reply via email to

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