[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Use of $@
From: |
alex xmb ratchev |
Subject: |
Re: Use of $@ |
Date: |
Tue, 21 Feb 2023 11:49:38 +0100 |
On Tue, Feb 21, 2023, 11:39 AM alex xmb ratchev <fxmbsw7@gmail.com> wrote:
>
>
> On Tue, Feb 21, 2023, 11:28 AM Christof Warlich <cwarlich@gmx.de> 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")
>>
>
thers couple ways , to try to list some
[[ -v varname ]] is an exisrancy check
there are three states
unset
set
set and not empty
the [[ -v will true on both set s
[[ $var ]] will true if var is not empty
then there is var expansion extensions
${var+else} prints else is var is set , or $var , if set
${var-else} returns else if var is unset , or $var
${var:+else} will print else if var is not empty , or $var
${var:-else} returns else when var is not empty , or $var
the same can do assignments
: "
${avar:=${1:-default}}
${other:=${third:-default2}}
${third:=other default}
"
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?
>>
>
> cat pidx ; printf \###\\n ; bash pidx unset -v arr
> arr=( 0 1 2 3 )
> pidx() {
> declare -n n=$1 ; declare e=$2
> [[ -v n[e] ]] &&
> printf '%s in %s .. yes\n' "$2" "$1"
> }
>
> pidx2() {
> [[ -v $1[$2] ]]
> }
>
> pidx arr 1 ; pidx arr 4
> pidx2 arr 3 && echo ye ; pidx2 arr 5 && echo ye
> ###
> 1 in arr .. yes ye
>
> see it as checking , on common criterias
> data looping , and copying , is cpu/hard
>
> Cheers,
>>
>> Chris
>>
>