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

Example 10−26. Using command substitution to generate the case variable<br />

#!/bin/bash<br />

# Using command substitution to generate a "case" variable.<br />

case $( arch ) in # "arch" returns machine architecture.<br />

i386 ) echo "80386−based machine";;<br />

i486 ) echo "80486−based machine";;<br />

i586 ) echo "Pentium−based machine";;<br />

i686 ) echo "Pentium2+−based machine";;<br />

* ) echo "Other type of machine";;<br />

esac<br />

exit 0<br />

A case construct can filter strings for globbing patterns.<br />

Example 10−27. Simple string matching<br />

#!/bin/bash<br />

# match−string.sh: simple string matching<br />

match_string ()<br />

{<br />

MATCH=0<br />

NOMATCH=90<br />

PARAMS=2 # Function requires 2 arguments.<br />

BAD_PARAMS=91<br />

}<br />

[ $# −eq $PARAMS ] || return $BAD_PARAMS<br />

case "$1" in<br />

"$2") return $MATCH;;<br />

* ) return $NOMATCH;;<br />

esac<br />

a=one<br />

b=two<br />

c=three<br />

d=two<br />

match_string $a # wrong number of parameters<br />

echo $? # 91<br />

match_string $a $b # no match<br />

echo $? # 90<br />

match_string $b $d # match<br />

echo $? # 0<br />

exit 0<br />

Chapter 10. Loops and Branches 120

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

Saved successfully!

Ooh no, something went wrong!