[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Some incorrect behaviour for BASH arrays
From: |
Kerin Millar |
Subject: |
Re: Some incorrect behaviour for BASH arrays |
Date: |
Thu, 31 Aug 2023 16:13:09 +0100 |
On Thu, 31 Aug 2023 01:12:48 +0700
Victor Pasko <victor.pasko@gmail.com> wrote:
> Hi,
>
> On my Win-7 64-bit using Cygwin
>
>
> *% bash --version*GNU bash, version 5.2.15(3)-release (x86_64-pc-cygwin)
> Copyright (C) 2022 Free Software Foundation, Inc.
> License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html
> >
>
> This is free software; you are free to change and redistribute it.
> There is NO WARRANTY, to the extent permitted by law.
>
>
> *% echo LANG=$LANG; echo LC_ALL=$LC_ALL*LANG=
> LC_ALL=
>
> Attached please find bug.bash to reproduce incorrect BASH behaviour for
> BASH arrays
> and look at ways to run it
This script is a mess because its functions begin by defining RESULT as an
ordinary, non-array variable (if not yet declared).
$ RESULT='string'
$ declare -p RESULT # not yet an array variable
declare -- RESULT='string'
It then proceeds to operate on the variable in such a way that it will be
transformed to an array.
$ RESULT[1]='second element'
$ declare -p RESULT
declare -a RESULT=([0]="string" [1]="second element")
Now, would RESULT='' empty this array? No, it would not.
$ RESULT='' # no different from RESULT[0]=''
$ declare -p RESULT
declare -a RESULT=([0]="" [1]="second element")
A correct way to initialise an empty array variable is RESULT=().
$ RESULT=()
$ declare -p RESULT # now an empty array
declare -a RESULT=()
You might also consider using the "local" builtin to declare the variable with
a function-local scope.
$ f() { local RESULT=(); RESULT+=("append me"); declare -p RESULT; }; unset -v
RESULT; f; declare -p RESULT
declare -a RESULT=([0]="append me")
bash: declare: RESULT: not found
Note that the second declare command correctly raises an error because RESULT
is not visible in its scope. Used judiciously, local can help to avoid the
writing of needless bugs.
--
Kerin Millar