help-bash
[Top][All Lists]
Advanced

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

Re: Use of $@


From: Andreas Kusalananda Kähäri
Subject: Re: Use of $@
Date: Tue, 21 Feb 2023 11:49:15 +0100

On Tue, Feb 21, 2023 at 11:43:24AM +0100, Kusalananda Kähäri wrote:
> On Tue, Feb 21, 2023 at 11:27:36AM +0100, Christof Warlich wrote:
> > Hi,
> > 
> > just to improve my bash skills: The following functions prints the array
> > index of a value if found:
> > 
> > index() { local e="$1"; shift; local a=("$@"); for i in "${!a[@]}"; do
> > [[ ${a[$i]} != $e ]] || { echo $i; break; }; done; }
> > 
> > Thus, with e.g.: myarray=("a" "bc" "my value" "z")
> > 
> > I get:
> > 
> > $ index "my value" "${myarray[@]}"
> > 2
> > 
> > as expected. The only thing that bothers me is that I couldn't get away
> > without the intermediate assignment of $@ to a new array (a): Is there
> > really no way to avoid that, i.e. directly using $@ in the for-loop?
> > 
> > Cheers,
> > 
> > Chris
> 
> You don't have to mention $@ at all, just shift elements off from the
> list until you find the one you're looking for, or until the list is
> empty. The below implementation returns a non-zero exit status (and no
> output) if the string isn't found.
> 
> index () {
>       local query="$1"; shift
>       local index=0
> 
>       until [ "$#" -eq 0 ] || [ "$1" = "$query" ]
>       do
>               index=$(( index + 1 ))
>               shift
>       done
> 
>       [ "$#" -ne 0 ] && printf '%s\n' "$index"
> }

Shorter, using the fact that shift retuns an exit value that we can use
to detect the end of the list.

index () {
        local query="$1"
        local index=0

        until ! shift || [ "$1" = "$query" ]
        do
                index=$(( index + 1 ))
        done

        [ "$#" -ne 0 ] && printf '%s\n' "$index"
}

... but it may be a bit too cryptic for going into code that more than
one person will have to maintain.

> 
> arr=( a bc "my value" z )
> 
> if ! index "my value" "${arr[@]}"
> then
>       echo 'not found' >&2
> fi
> 
> -- 
> Andreas (Kusalananda) Kähäri
> SciLifeLab, NBIS, ICM
> Uppsala University, Sweden
> 
> .

-- 
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden

.



reply via email to

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