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 10−28. Checking for alphabetic input<br />

#!/bin/bash<br />

# isalpha.sh: Using a "case" structure to filter a string.<br />

SUCCESS=0<br />

FAILURE=−1<br />

isalpha () # Tests whether *first character* of input string is alphabetic.<br />

{<br />

if [ −z "$1" ]<br />

# No argument passed?<br />

then<br />

return $FAILURE<br />

fi<br />

case "$1" in<br />

[a−zA−Z]*) return $SUCCESS;; # Begins with a letter?<br />

* ) return $FAILURE;;<br />

esac<br />

} # Compare this with "isalpha ()" function in C.<br />

isalpha2 () # Tests whether *entire string* is alphabetic.<br />

{<br />

[ $# −eq 1 ] || return $FAILURE<br />

}<br />

case $1 in<br />

*[!a−zA−Z]*|"") return $FAILURE;;<br />

*) return $SUCCESS;;<br />

esac<br />

isdigit () # Tests whether *entire string* is numerical.<br />

{ # In other words, tests for integer variable.<br />

[ $# −eq 1 ] || return $FAILURE<br />

}<br />

case $1 in<br />

*[!0−9]*|"") return $FAILURE;;<br />

*) return $SUCCESS;;<br />

esac<br />

check_var () # Front−end to isalpha ().<br />

{<br />

if isalpha "$@"<br />

then<br />

echo "\"$*\" begins with an alpha character."<br />

if isalpha2 "$@"<br />

then # No point in testing if first char is non−alpha.<br />

echo "\"$*\" contains only alpha characters."<br />

else<br />

echo "\"$*\" contains at least one non−alpha character."<br />

fi<br />

else<br />

echo "\"$*\" begins with a non−alpha character."<br />

# Also "non−alpha" if no argument passed.<br />

fi<br />

echo<br />

Chapter 10. Loops and Branches 121

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

Saved successfully!

Ooh no, something went wrong!