Saraswati gangwar
Saraswati gangwar

Reputation: 11

Assign value to array in bash

I am learning shell sripting and got stuck. here is the code #!/bin/bash

a=0
myarray[$a]=$1
echo $myarray[$a]
((a+=1))
echo $a

Output:

#./varcheck sa
sa[0]
1

somebody please tell me why the name of array is getting replaced with argument that I want to assign to 0th index of array.

Upvotes: 0

Views: 41

Answers (1)

kojiro
kojiro

Reputation: 77107

echo "${myarray[$a]}"

is how you output an array member. Alternatively

echo "${myarray[a]}"

since the index is guaranteed to be arithmetic context unless you're using associative arrays. Thus, you could actually remove a line:

a=0
myarray[a]=$1
echo "${myarray[a++]}" # Get element at zeroth index
echo $a # Get post-incremented expansion of a.

Upvotes: 4

Related Questions