יום שני, 10 ביוני 2013

Array manipulation in bash

The following is a simple array manipulation in bash: 

  1: #Create a new array 
  2: 
  3: declare -a Animales =('Dog' 'Cat' 'Hourse' 'Monkey' );
  4: 
  5: Animales[4] = 'Pig'
  6: 
  7: #print the Hourse
  8: echo  ${Animales[2]}
  9: 
 10: #The total no of animales in the array 
 11: 
 12: echo ${#Animales[@]} 
 13: 
 14: #get the 2th and the 3rt elements 
 15: 
 16: echo ${Animales[@]:2:2}
 17: 
 18: #Replacing Cat with Lion
 19: 
 20: echo ${Animales[@]/Cat/Lion}
 21: 
 22: #Firing the Dog 
 23: 
 24: unset Animales[0]

We can  although loop over the array

  1: #loop over the array 
  2: for i in "${Animales[@]}"
  3: do
  4:   echo $i
  5: done
  6: #loop over the array last 3 elements 
  7: for i in "${Animales[@]:2:3}"
  8: do
  9:   echo $i
 10: done


Resources:
http://www.thegeekstuff.com/2010/06/bash-array-tutorial/
http://www.cyberciti.biz/faq/bash-for-loop-array/

אין תגובות:

הוסף רשומת תגובה