help-bash
[Top][All Lists]
Advanced

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

Re: Invisible contents of a variable array?


From: David
Subject: Re: Invisible contents of a variable array?
Date: Sat, 21 Jan 2023 15:51:37 +1100

On Sat, 21 Jan 2023 at 15:24, Roger <rogerx.oss@gmail.com> wrote:
> > On Fri, Jan 20, 2023 at 09:19:30PM -0500, Greg Wooledge wrote:
> >On Fri, Jan 20, 2023 at 08:54:47PM -0500, Roger wrote:

> Bingo!  declare -p was the magic for showing _files[0] as a the null string!

_files[0] = null string is only there because you put it there.

The assignment that you gave at the end of your 'declare' command
is what created the first element.

Demo:

$ unset _files
$ declare -a _files=""
$ declare -p _files
declare -a _files=([0]="")

If you don't want that first empty entry then don't create it.

Demo:

[david@kablamm ~]$ unset _files
[david@kablamm ~]$ declare -a _files
[david@kablamm ~]$ declare -p _files
declare -a _files

That's what the declare -p output of an empty indexed-array looks like.

> Without pasting a whole mess of code, what I'm doing is using getopts for
> parsing the dash arguments.  Then shifting for parsing the additional 
> specified
> files/folders.
>
> # remove already processed getopts parameters.
> shift $((${OPTIND}-1))
> declare _file=""
> declare -a -g _files=""

Change that line to
declare -a _files

Or, don't even declare the array. Just initialise it:

_files=( )

> # then loop over the additional specified files
> i=1
> for _file do
>     echo "  DEBUG: var FILE ${i}: ${_file}"
>     _files[$i]="${_file}"
>     i=$((i + 1))
> done

To add elements to a _files array:

_files+=( file1 file2 )

To read elements from _files array:

for f in "${_files[@]}" ; do
    echo "${f}"
done

To increment an integer value:

>     i=$((i + 1))

(( ++i ))

etc ...



reply via email to

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