[Top][All Lists]

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

Re: Use of $@

From: Greg Wooledge
Subject: Re: Use of $@
Date: Tue, 21 Feb 2023 07:35:27 -0500

On Tue, Feb 21, 2023 at 11:27:36AM +0100, Christof Warlich wrote:
> just to improve my bash skills: The following functions prints the array
> index of a value if found:
> Thus, with e.g.: myarray=("a" "bc" "my value" "z")
> $ index "my value" "${myarray[@]}"
> 2
> 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?

unicorn:~$ cat foo

index() {
    local i needle="$1"
    for ((i=1; i <= $#; i++)); do
        if [[ ${!i} = "$needle" ]]; then
            echo "$((i-1))"
            return 0
    return 1

index zebra horse horse horse zebra horse || echo "not found"
index zebra horse zebra || echo "not found"
index zebra horse horse || echo "not found"

unicorn:~$ ./foo
not found

reply via email to

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