Posted mostly for my own reference since I always forget the syntax, arrays are invaluable when writing moderately complex shell scripts. If you're writing any serious shell scripts you'll want to refer The Linux Documentation Project's excellent primers: Bash Guide for Beginners and Advanced Bash-Scripting Guide
array.sh
#!/bin/bash
echo "<<< Load a file into an array"
echo "# Set the IFS (Internal Field Separator) to a newline
IFS='
'
# Load file.txt from the current directory
arr=( \$( < file.txt ) )
"
IFS='
'
arr=( $( < file.txt ) )
echo "<<< Addressing individual array elements"
echo "\${arr[0]} = ${arr[0]}" # the first line of the file
echo "\${arr[1]} = ${arr[1]}" # the second line of the file
echo ""
echo "<<< \${#VARNAME[@]} will always return the number of elements in an array"
echo "\$arr contains ${#arr[@]} (\${#arr[@]}) items"
echo ""
echo "<<< Loop through the array (\${arr[@]}), loading each item as \$foo."
num=1
for foo in "${arr[@]}" ; do
echo "Loop iteration $num: $foo"
num=$((num+1))
done
echo ""
echo "<<< Loop through the array, addressing each item with an index"
num=0
while [[ $num -lt ${#arr[@]} ]] ; do
echo "Array index $num (\${arr[$num]}): ${arr[$num]}"
num=$((num+1))
donefile.txt
file line 1 file line 2 file line 3 file line 4
Saving the two files above as array.sh and file.txt, and running array.sh yields:
$./array.sh
<<< Load a file into an array
# Set the IFS (Internal Field Separator) to a newline
IFS='
'
# Load file.txt from the current directory
arr=( $( < file.txt ) )
<<< Addressing individual array elements
${arr[0]} = file line 1
${arr[1]} = file line 2
<<< ${#VARNAME[@]} will always return the number of elements in an array
$arr contains 4 (${#arr[@]}) items
<<< Loop through the array (${arr[@]}), loading each item as $foo.
Loop iteration 1: file line 1
Loop iteration 2: file line 2
Loop iteration 3: file line 3
Loop iteration 4: file line 4
<<< Loop through the array, addressing each item with an index
Array index 0 (${arr[0]}): file line 1
Array index 1 (${arr[1]}): file line 2
Array index 2 (${arr[2]}): file line 3
Array index 3 (${arr[3]}): file line 4
Tags: array, bash, Linux, scripting



December 5th, 2011 at 4:16 am
Packaging Machinery…
Very informative blog. Thank you for sharing this information, please do keep updates….