1

I am learning array by following code

source_array_list[0]="a"
source_array_list[1]="a"
source_array_list[2]="a"
source_array_list[3]="a"
source_array_list[4]="a"
source_array_list[5]="a"
source_array_list[6]="a"
source_array_list[7]="a"
a=0
while [$a -le 6]
do
    echo "just before loop"
    target_array[a]=source_array_list[$a]
    echo "${source_array_list[$a]}"
    a=`expr $a + 1`
done

Now this is not working and giving the error [0: not found.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
Aman
  • 1,201

1 Answers1

4

You need a space after '[' because '[' is a command.

Refer here - https://stackoverflow.com/questions/9581064/why-should-be-there-a-space-after-and-before-in-the-bash-script

You also need ${} around the array variable reference, so you should have:

source_array_list[0]="a"
source_array_list[1]="b"
source_array_list[2]="c"
source_array_list[3]="d"
source_array_list[4]="e"
source_array_list[5]="f"
source_array_list[6]="g"
source_array_list[7]="h"
while [ $a -le 6 ]
do
  target_array[a]=${source_array_list[$a]}
  echo "${source_array_list[$a]}"
  a=`expr $a + 1`
done

You could also simplify this a bit by doing the following below,

source_array_list=('a' 'b' 'c' 'd' 'e' 'f' 'g' 'h')
target_array=()
for element in "${source_array_list[@]}"
do
  target_array+=(${element})
  echo "${element}"
done
echo ${target_array[@]}
M.S.Arun
  • 291
balder
  • 156