[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] New conditional evaluation with a regex
From: |
Eric Blake |
Subject: |
Re: [Help-bash] New conditional evaluation with a regex |
Date: |
Thu, 08 Dec 2011 06:31:49 -0700 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:8.0) Gecko/20111115 Thunderbird/8.0 |
On 12/08/2011 03:49 AM, Jesse Molina wrote:
>
> Duh.
>
> I could use case.
Yep. But while we're on the topic:
>
> case "$TEST1" in
Here, you don't need "" around $TEST1, since no shell performs word
splitting or filename expansion here.
> 2|3|4|5|6|7)
And if you're going for conciseness, it is portable to write:
case $TEST1 in
[2-7]) ...
Note that ranges inside [] are only portable if you use LC_ALL=C, or if
the range is strictly numeric and not alphabetic; as alphabetic ranges
are undefined in other locales.
>> The first way to do this uses single [] brackets and I'll break it up
>> for readability;
>>
>> if [ \
>> "$TEST1" == 2 \
>> -o "$TEST1" == 3 \
>> -o "$TEST1" == 4 \
>> -o "$TEST1" == 5 \
>> -o "$TEST1" == 6 \
>> -o "$TEST1" == 7 \
>> ] ; then
Not portable. Use of -o and -a inside [ ] (or test) is a disaster
waiting to happen in code trying to be portable. Likewise, with [ ],
the portable spelling is '=', not '=='.
>> Then, I remembered that you could use =~ to do something like that, but
>> I had to google up to remember that you can only do it in double [[]]
>> brackets (new style);
>>
>> if [[ "$TEST1" =~ 2|3|4|5|6|7 ]] ; then
Again, non-portable if your script is ever run on just a POSIX /bin/sh
(although there is an effort underway to add [[ ]] to the next version
of POSIX, several years down the road).
>> Any other clever ways to do complex conditional tests, or neat tricks on
>> the subject?
For ranges, you could have used numeric comparison operators in [ ]:
if [ "$TEST1" -ge 2 ] && [ "$TEST1" -le 7 ]; then
...
--
Eric Blake address@hidden +1-919-301-3266
Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature