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.

  • 3
    You need spaces in [...] operator while [ $a -le 6 ]. – cuonglm Apr 2 '15 at 13:04
  • You want to run the [ command, not the [0 command. – Stéphane Chazelas Apr 2 '15 at 13:11
  • You can streamline this a little: a=`expr $a + 1` can be changed to ((a++)). – Scott Apr 2 '15 at 20:14
3

you need a space after '[' because '[' is a command see 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

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[@]}

Not the answer you're looking for? Browse other questions tagged or ask your own question.