Bash Array

Assign Array Elements

# Assign array elements
echo
myArr[0]='one'
myArr[1]='two'
myArr[10]='ten'
# Access array elements. *Curly brackets* are important.
echo "\${myArr[0]}: ${myArr[0]}"  # ${myArr[0]}: one.
# Echo all elements
echo "\${myArr[@]}: ${myArr[@]}" # ${myArr[@]}: one two ten
 
# Initialize array
echo
myArr3=( one two three four )
# Echo all elements
echo "\$myArr3[@]: ${myArr3[@]}" # $myArr3[@]: one two three four
# Number of array elements
echo "\$#myArr3[@]: ${#myArr3[@]}" # $#myArr3[@]: 4
 
# Initialize array
echo
myStr2='one two three four'
myArr2=( $myStr2 )
# Echo all elements
echo "\${myArr2[@]}: ${myArr2[@]}" # ${myArr2[@]}: one two three four

Tokenize String Into Array

myString2=one:two::four
oldIFS=$IFS
IFS=:
myArr2=( $myString2 )
IFS=$oldIFS
echo ${myArr2[0]}  # Output: 'one'
echo ${myArr2[1]}  # Output: 'two'
echo ${myArr2[2]}  # Output: ''
echo ${myArr2[3]}  # Output: 'four'

Loop Through Array Elements

myStrings='string1 string2 string3'
myStringArray=( ${myStrings} )
for myString in "${myStringArray[@]}"
do
  echo "${myString}"
done

Example: Backup Multiple Directories

#!/bin/sh
backup_root=$HOME
curr_dir=`pwd`
curr_ts=`date +"%m-%d-%y_%H-%M-%S"`
curr_backup_dir=${backup_root}/backup/${curr_ts}
mkdir -p ${curr_backup_dir}
 
dirs_to_backup='tomcat lib'
dirs=( ${dirs_to_backup} )
for d in "${dirs[@]}"
do
  cd ${backup_root}
  echo "Backing up ${d} to ${curr_backup_dir}..."
  tar --exclude="logs" --exclude="work" --exclude="temp" -pzcvf ${curr_backup_dir}/${d}.tar ${d}
done
 
cd ${curr_dir}
echo "done."

References

http://tldp.org/LDP/abs/html/arrays.html

This entry was posted in shell. Bookmark the permalink.