Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 2266  / 3 Years ago, sun, september 19, 2021, 4:24:07

I am trying to output the values of array element but I am getting weird output. Please have a look at it and help me solve it. Thank you.



n=2
declare -a myarray[$n]
myarray[0]=hey
myarray[1]=hello
myarray[2]=bye
for i in ${myarray[@]}
do
echo $i
done


Output:



robin@robin-VirtualBox:~/lx$ sh array.sh
array.sh: 2: array.sh: declare: not found
array.sh: 3: array.sh: myarray[0]=hey: not found
array.sh: 4: array.sh: myarray[1]=hello: not found
array.sh: 5: array.sh: myarray[2]=bye: not found
array.sh: 6: array.sh: Bad substitution

More From » bash

 Answers
6

declare is a bash shell builtin, and is not defined in the sh shell.



So, you must to run your script using the following command:



bash array.sh


Or add, the following shebang line at the start of your script:



#!/bin/bash


Be sure that your script is exectutable:



 chmod +x array.sh


And run it using the following command:



./array.sh

[#25635] Tuesday, September 21, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
odenanno

Total Points: 207
Total Questions: 113
Total Answers: 94

Location: South Korea
Member since Sat, Oct 2, 2021
3 Years ago
;