Wednesday, October 8, 2014

Covert string variable to array in bash script

The syntax is:
   array=($string)

Following is an example:
   string="where am I?"
   array=($string)

Check:
   for i in ${array[@]}; do echo $i; done
   where
   am
   I?

Convert array to string variable:
   for i in ${array[@]}; do abc="$abc `echo $i`"; done

Check:
   echo $abc
   where am I?

Additional array info:
   ${arr[*]} # All of the items in the array
   ${!arr[*]} # All of the indexes in the array
   ${#arr[*]} # Number of items in the array
   ${#arr[0]} # Length of item zero

Append new element to array:
   arr=(${arr[@]} element)
   arr+=(element)

No comments: