27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

Example 26−10. Simulating a two−dimensional array, then tilting it<br />

#!/bin/bash<br />

# Simulating a two−dimensional array.<br />

# A two−dimensional array stores rows sequentially.<br />

Rows=5<br />

Columns=5<br />

declare −a alpha<br />

# char alpha [Rows] [Columns];<br />

# Unnecessary declaration.<br />

load_alpha ()<br />

{<br />

local rc=0<br />

local index<br />

for i in A B C D E F G H I J K L M N O P Q R S T U V W X Y<br />

do<br />

local row=`expr $rc / $Columns`<br />

local column=`expr $rc % $Rows`<br />

let "index = $row * $Rows + $column"<br />

alpha[$index]=$i # alpha[$row][$column]<br />

let "rc += 1"<br />

done<br />

# Simpler would be<br />

# declare −a alpha=( A B C D E F G H I J K L M N O P Q R S T U V W X Y )<br />

# but this somehow lacks the "flavor" of a two−dimensional array.<br />

}<br />

print_alpha ()<br />

{<br />

local row=0<br />

local index<br />

echo<br />

while [ "$row" −lt "$Rows" ]<br />

do<br />

local column=0<br />

# Print out in "row major" order −<br />

# columns vary<br />

# while row (outer loop) remains the same.<br />

while [ "$column" −lt "$Columns" ]<br />

do<br />

let "index = $row * $Rows + $column"<br />

echo −n "${alpha[index]} " # alpha[$row][$column]<br />

let "column += 1"<br />

done<br />

let "row += 1"<br />

echo<br />

done<br />

# The simpler equivalent is<br />

# echo ${alpha[*]} | xargs −n $Columns<br />

echo<br />

}<br />

Chapter 26. Arrays 307

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!