Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
BASH array example
01-11-2010, 03:11 PM
Post: #1
BASH array example
Here is a example of arrays in bash.
Code:
#!/bin/bash

#arrays in bash can be in any order as you see below I have myarray with only indexs of 2 4 10
myarray[2]='second'
myarray[4]='forth'
myarray[10]='tenth'
myarray[17]=17

#when returning a value from a rray you muyst have ${} around it
echo '${myarray[2]}'
echo ${myarray[2]}

#if you try to call a array index that was not initialize you will just be return a blank
echo '${myarray[1]}'
echo ${myarray[1]}

#to display all the items in a array you can do as follows
echo '${myarray[@]}'
echo ${myarray[@]}

#another way to display all the items in a array you can use the *
echo '${myarray[*]}'
echo ${myarray[*]}

#to loop through a array in a for loop do as follows. This is useful if you want to do something to each single element
echo 'array for loop example'
for x in ${myarray[@]}
do
    echo $x
done


Attached File(s)
.zip  bashArrayExamp.zip (Size: 955 bytes / Downloads: 3)
Visit this user's website Find all posts by this user
Quote this message in a reply
01-18-2010, 09:11 PM
Post: #2
RE: BASH array example
One difference I notice here as opposed to some languages is bash arrays grow dynamically.
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: