[Top][All Lists]

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

Re: How case statement is tested?

From: Eric Blake
Subject: Re: How case statement is tested?
Date: Wed, 11 Mar 2020 12:55:01 -0500
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Thunderbird/68.5.0

On 3/11/20 11:47 AM, Peng Yu wrote:

I am wondering if there is any optimization in testing the conditions
in a case statement?

What optimization(s) do you have in mind? Bash has to perform glob-matching for each potential pattern. Anything you can do to speed up globbing (such as recognizing when a glob can only match a literal string) might help, but since side effects are possible in specifying a glob pattern, there's very little you can do to parallelize things by testing multiple glob patterns at once. For example:

x= y=
case 1 in
  $((x=0)) ) ;;
  $((y=1)) ) ;;
  $((x=1)) ) ;;
echo "$x.$y"

must output 0.1, which means you cannot precompute the pattern for the third clause bounded by $((x=1)) (which is really the glob '1' plus the side-effect of setting x=1) until after you have already ascertained whether the first two clauses did not match.

Or it is just like a series of if-statement and each condition must be
tested until one condition is true? Thanks.

This, with the additional complication that you can skip conditions (with ';&') or evaluate more than one condition as true (with ';;&'). See if you can figure out what this will output prior to running it:

for var in a b c d; do
  case $var in
    a) echo 1 ;;&
    b) echo 2 ;&
    c) echo 3 ;;
    *) echo 4

Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3226
Virtualization: |

reply via email to

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