arrayszsh

zsh: check if string is in array


E.g.

foo=(a b c)

Now, how can I do an easy check if b is in $foo?


Solution

  • You can use reverse subscripting as per the following transcript:

    pax$ foo=(a b c)
    
    pax$ if [[ ${foo[(r)b]} == b ]] ; then ; echo yes ; else ; echo no ; fi
    yes
    
    pax$ if [[ ${foo[(r)x]} == x ]] ; then ; echo yes ; else ; echo no ; fi
    no
    

    You'll find the datails under man zshparam under Subscript Flags (at least in zsh 4.3.10 under Ubuntu 10.10).


    Alternatively (thanks to geekosaur for this), you can use:

    pax$ if [[ ${foo[(i)b]} -le ${#foo} ]] ; then ; echo yes ; else ; echo no ; fi
    

    You can see what you get out of those two expressions by simply doing:

    pax$ echo ${foo[(i)a]} ${#foo}
    1 3
    
    pax$ echo ${foo[(i)b]} ${#foo}
    2 3
    
    pax$ echo ${foo[(i)c]} ${#foo}
    3 3
    
    pax$ echo ${foo[(i)d]} ${#foo}
    4 3