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...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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

echo −n "area2[0] = "<br />

echo ${area2[0]}<br />

# Aha, zero−based indexing (first element of array is [0], not [1]).<br />

echo −n "area2[1] = "<br />

echo ${area2[1]} # [1] is second element of array.<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

echo; echo; echo<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

# Yet another array, "area3".<br />

# Yet another way of assigning array variables...<br />

# array_name=([xx]=XXX [yy]=YYY ...)<br />

area3=([17]=seventeen [24]=twenty−four)<br />

echo −n "area3[17] = "<br />

echo ${area3[17]}<br />

echo −n "area3[24] = "<br />

echo ${area3[24]}<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

exit 0<br />

Bash permits array operations on variables, even if the variables are not explicitly<br />

declared as arrays.<br />

string=abcABC123ABCabc<br />

echo ${string[@]}<br />

echo ${string[*]}<br />

echo ${string[0]}<br />

echo ${string[1]}<br />

# abcABC123ABCabc<br />

# abcABC123ABCabc<br />

# abcABC123ABCabc<br />

# No output!<br />

# Why?<br />

echo ${#string[@]} # 1<br />

# One element in the array.<br />

# The string itself.<br />

# Thank you, Michael Zick, for pointing this out.<br />

Once again this demonstrates that Bash variables are untyped.<br />

Example 26−2. Formatting a poem<br />

#!/bin/bash<br />

# poem.sh<br />

# Lines of the poem (single stanza).<br />

Line[1]="I do not know which to prefer,"<br />

Line[2]="The beauty of inflections"<br />

Line[3]="Or the beauty of innuendoes,"<br />

Line[4]="The blackbird whistling"<br />

Line[5]="Or just after."<br />

# Attribution.<br />

Attrib[1]=" Wallace Stevens"<br />

Chapter 26. Arrays 293

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

Saved successfully!

Ooh no, something went wrong!