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

Attrib[2]="\"Thirteen Ways of Looking at a Blackbird\""<br />

for index in 1 2 3 4 5 # Five lines.<br />

do<br />

printf " %s\n" "${Line[index]}"<br />

done<br />

for index in 1 2<br />

do<br />

printf "<br />

done<br />

# Two attribution lines.<br />

%s\n" "${Attrib[index]}"<br />

exit 0<br />

Array variables have a syntax all their own, and even standard Bash commands and operators have special<br />

options adapted for array use.<br />

array=( zero one two three four five )<br />

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

echo ${array:0}<br />

echo ${array:1}<br />

# zero<br />

# zero<br />

# Parameter expansion of first element.<br />

# ero<br />

# Parameter expansion of first element,<br />

#+ starting at position #1 (2nd character).<br />

echo ${#array} # 4<br />

# Length of first element of array.<br />

In an array context, some Bash builtins have a slightly altered meaning. For example, unset deletes array<br />

elements, or even an entire array.<br />

Example 26−3. Some special properties of arrays<br />

#!/bin/bash<br />

declare −a colors<br />

# Permits declaring an array without specifying its size.<br />

echo "Enter your favorite colors (separated from each other by a space)."<br />

read −a colors # Enter at least 3 colors to demonstrate features below.<br />

# Special option to 'read' command,<br />

#+ allowing assignment of elements in an array.<br />

echo<br />

element_count=${#colors[@]}<br />

# Special syntax to extract number of elements in array.<br />

# element_count=${#colors[*]} works also.<br />

#<br />

# The "@" variable allows word splitting within quotes<br />

#+ (extracts variables separated by whitespace).<br />

index=0<br />

while [ "$index" −lt "$element_count" ]<br />

do # List all the elements in the array.<br />

Chapter 26. Arrays 294

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

Saved successfully!

Ooh no, something went wrong!