0
#!/bin/bash 
arrck=
arrrlt=

if true; then
arrck+=("1")
arrrlt+=("one")
else
    echo "something"
fi 

for i in ${!arrck[*]} 
do
    echo "${arrck[i]} is ${arrrlt[i]}"
done


output 1-- 

 is
1 is one

output 2--tracing on  

 ./Building_block.sh
+ arrck=
+ arrrlt=
+ true
+ arrck+=("1")
+ arrrlt+=("one")
+ for i in '${!arrck[*]}'
+ echo ' is '
 is
+ for i in '${!arrck[*]}'
+ echo '1 is one'
1 is one

Why is the loop running with no value assigned to i ? i can say it tried to execute echo "${arrck[]} is ${arrrlt[]}" and picking the blank space as value.

5
  • after commenting the declaration, it is running as expected just 1 time( length of the array) ``` arrck= arrrlt= ``` Commented Aug 29, 2019 at 20:46
  • There are 2 cells/elements in the array: echo ${!arrck[@]} ==> 0 1 Commented Aug 29, 2019 at 20:47
  • arrck=() arrrlt=() , also sloved the issue. Commented Aug 29, 2019 at 20:56
  • The first two lines of the script don't do anything useful. Commented Aug 29, 2019 at 21:03
  • @chepner but they do create an initial cell with index 0 for the 2 arrays arrck and arrrlt Commented Aug 29, 2019 at 21:03

1 Answer 1

2

When you assign a value to a variable you are actually assigning a value to cell/position 0 in an array, eg:

$ x=5

$ echo ${x}
5

$ echo ${!x[@]}
0

$ echo ${x[0]}
5

$ echo ${x[@]}
5

In your example the first set of commands assign the empty string to index position '0' of the 2 arrays arrck[] and arrrlt[]:

$ arrck=
$ arrrlt=

$ echo "${!arrck[@]} : ${!arrrlt[@]}"
0 : 0

The if/then/else block then appends a second set of values to your arrays with indexes 1 and values of 1 and one.

The for loop then loops through the 2 available indices for the arrck[] array, namely 0 and 1.

What you probably want to do is start out by dropping/deallocating your arrays (as opposed to creating cell 0), eg:

$ unset arrck
$ unset arrrlt
$ echo "${!arrck[@]:-undefined} : ${!arrrlt[@]:-undefined}"
undefined : undefined
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.