Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

I am new to unix shell 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. Please guide me to solve it.

share|improve this question

marked as duplicate by Gilles Apr 2 at 21:56

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

1 Answer 1

up vote 3 down vote accepted

you need a space after '[' because '[' is a command see here http://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[@]}
share|improve this answer

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