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

The array=( element1 element2 ... elementN ) initialization operation, with the help of command<br />

substitution, makes it possible to load the contents of a text file into an array.<br />

#!/bin/bash<br />

filename=sample_file<br />

# cat sample_file<br />

#<br />

# 1 a b c<br />

# 2 d e fg<br />

declare −a array1<br />

array1=( `cat "$filename" | tr '\n' ' '`) # Loads contents<br />

# of $filename into array1.<br />

# list file to stdout.<br />

# change linefeeds in file to spaces.<br />

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

# List the array.<br />

# 1 a b c 2 d e fg<br />

#<br />

# Each whitespace−separated "word" in the file<br />

#+ has been assigned to an element of the array.<br />

element_count=${#array1[*]}<br />

echo $element_count # 8<br />

Clever scripting makes it possible to add array operations.<br />

Example 26−5. Copying and concatenating arrays<br />

#! /bin/bash<br />

# CopyArray.sh<br />

#<br />

# This script written by Michael Zick.<br />

# Used here with permission.<br />

# How−To "Pass by Name & Return by Name"<br />

#+ or "Building your own assignment statement".<br />

CpArray_Mac() {<br />

# Assignment Command Statement Builder<br />

echo −n 'eval '<br />

echo −n "$2"<br />

echo −n '=( ${'<br />

echo −n "$1"<br />

echo −n '[@]} )'<br />

# Destination name<br />

# Source name<br />

# That could all be a single command.<br />

# Matter of style only.<br />

}<br />

declare −f CopyArray<br />

# Function "Pointer"<br />

Chapter 26. Arrays 298

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

Saved successfully!

Ooh no, something went wrong!