help-bash
[Top][All Lists]
Advanced

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

Re: How do we get state of a flag in set -o ...


From: Greg Wooledge
Subject: Re: How do we get state of a flag in set -o ...
Date: Tue, 11 Jul 2023 18:46:33 -0400

On Wed, Jul 12, 2023 at 12:24:38AM +0200, alex xmb ratchev wrote:
> On Wed, Jul 12, 2023, 12:15 AM Greg Wooledge <greg@wooledge.org> wrote:
> > All the talk of associative arrays and the   array=( key value ... )
> > syntax is just a digression.

That said....

> however myy biig problem with that story is .. im 100 sure i used such
> expandings many
> so this all breaks a bit my head
> i 100 remember way more -A .. $onevar than mixed multivars usage

The  array=( key value ... )  syntax was introduced in bash 5.1.

array=( "${list[@]}" )  where list expands to multiple words does not
do what you want it to do, neither in bash 5.1 nor 5.2.

unicorn:~$ bash-5.1
unicorn:~$ declare -A hash; str='two words'
unicorn:~$ hash=( $str )
unicorn:~$ declare -p hash
declare -A hash=(["two words"]="" )

Now, obviously you could throw in 'eval' into the picture, but then you
would need to use "${list[@]@Q}" or something.

unicorn:~$ list=( key1 '' key2 '[' key3 ']' key4 '$(date >&2)' )
unicorn:~$ unset -v hash; declare -A hash
unicorn:~$ eval 'hash=('"${list[@]@Q}"')'
unicorn:~$ declare -p hash
declare -A hash=([key4]="\$(date >&2)" [key2]="[" [key3]="]" [key1]="" )

This works, but it's not pretty.  It can be simplified down to

unicorn:~$ hash=()
unicorn:~$ eval "hash=(${list[@]@Q})"
unicorn:~$ declare -p hash
declare -A hash=([key4]="\$(date >&2)" [key2]="[" [key3]="]" [key1]="" )

but I think that's as good as it'll get.  You could also use a loop:

unicorn:~$ hash=()
unicorn:~$ for ((i=0; i < ${#list[@]}; i+=2)); do 
hash[${list[i]}]=${list[i+1]}; done
unicorn:~$ declare -p hash
declare -A hash=([key4]="\$(date >&2)" [key2]="[" [key3]="]" [key1]="" )

This is not pretty either, but some people may find it easier to read.
Others may not.

If you want elegant code, I think you're just using the wrong language.
I know I keep saying this, but that's because it keeps being true.
Other scripting languages handle cases like this *much* more elegantly.

Bash is not primarily a programming language.  It's primarily a shell.
All of these data structures are hacked in, on top of the 45-year-old
shell language.  Honestly it's amazing it does as well as it does.



reply via email to

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