Skip to main content

Thread: Shell Scripting Array Error


hi,

new shell scripting , facing problem. have following shell script file
php code:
#!/bin/sh
# step 1 : get the contents of the folder and fill the array
declare my_array=(`ls -l`)

# get number of elements in the array
elements=${#my_array[@]}

# echo each element in array ; for loop
for (( i=0;i<$elements;i++)); do
    echo ${
my_array[${i}]}
done 

# end 
when execute command directly in terminal 1 one, works fine , array filled contents of ls command. when create script file testscript.sh , execute in shell following error:

testscript.sh: 3: syntax error: "(" unexpected

can not figure out why getting error.

in advance,
kind regards

by starting script #!/bin/sh, using dash shell, not support arrays. reason error message. not receive error message in terminal window because shell bash. use #!/bin/bash in shell script.

put contents of directory array, there no need use ls command. use glob instead.

can list of array indices ${!my_array[@]}, simplifies script.

code:
#!/bin/bash  my_array=( * )  in ${!my_array[@]} ;   echo "${my_array[i]}" done
for excellent discussion of arrays, see:

http://mywiki.wooledge.org/bashfaq/005


Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk Shell Scripting Array Error


Ubuntu

Comments