4

The think is that I want to save something to an array in bash. The point is that I want one name of file for one array. So I don't know how much arrays I will have.

#!/bin/bash
declare -A NAMES
index=0
for a in recursive.o timeout.o print_recursive.o recfun.o
do
  NAMES[$index]=$a
  index=$((index+1))
  echo ${NAMES[ $index ]}  
done

When I run script with -x I can see that NAMES[$index], the index is not there represented as number so the whole thing doesn't work.

3 Answers 3

1

The error is at lines 7 and 8. Swap them and it will work.

When index have value 0 you set NAMES[0]=recursive.o, then increment index and print NAMES[1] which not set. And same thing for another elements. Because that there is no output.

Your loop should looks like this:

for a in recursive.o timeout.o print_recursive.o recfun.o
do
  NAMES[$index]=$a
  echo ${NAMES[$index]}
  index=$((index+1))
done
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, working but why? if i swap the lines i than i should be priting array [index++] where should be nothing.
@Vrsi How can you expect an element that hasn't been assigned a value to contain something?
1

The problem is in the following:

declare -A NAMES

This makes an associative array NAMES. Quoting from help declare:

Options which set attributes:
  -a        to make NAMEs indexed arrays (if supported)
  -A        to make NAMEs associative arrays (if supported)

You needed to say:

declare -a NAMES

2 Comments

Well sorry for that but its not the reason, I changed that because i had the same idea, but it doesnt help. Im thinking the problem is somewhere in syntax. But you are right there should be -a :)
@Vrsi You are attempting to print the value after incrementing the array index.
1

May be you are trying to do this:

#!/bin/bash

declare -a NAMES

for a in recursive.o timeout.o print_recursive.o recfun.o; do
    NAMES+=( "$a" )
done

for (( x=0; x<${#NAMES[@]}; x++ )); do
    echo "Index:$x has Value:${NAMES[x]}"
done

Output:

Index:0 has Value:recursive.o
Index:1 has Value:timeout.o
Index:2 has Value:print_recursive.o
Index:3 has Value:recfun.o

Accessing the index which is not set is throwing it off.

NAMES[$index]=$a        #Setting up an array with index 0
index=$((index+1))      #Incrementing the index to 1
echo ${NAMES[ $index ]} #Accessing value of index 1 which is not yet set

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.