LDP/LDP/guide/docbook/abs-guide/isalpha.sh

107 lines
2.1 KiB
Bash
Raw Permalink Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
2002-07-22 15:11:51 +00:00
# isalpha.sh: Using a "case" structure to filter a string.
2001-07-10 14:25:50 +00:00
SUCCESS=0
2012-11-27 14:56:18 +00:00
FAILURE=1 # Was FAILURE=-1,
#+ but Bash no longer allows negative return value.
2001-07-10 14:25:50 +00:00
isalpha () # Tests whether *first character* of input string is alphabetic.
{
2001-09-04 13:27:31 +00:00
if [ -z "$1" ] # No argument passed?
2001-07-10 14:25:50 +00:00
then
return $FAILURE
fi
case "$1" in
2007-04-26 21:13:49 +00:00
[a-zA-Z]*) return $SUCCESS;; # Begins with a letter?
* ) return $FAILURE;;
2001-07-10 14:25:50 +00:00
esac
2001-09-04 13:27:31 +00:00
} # Compare this with "isalpha ()" function in C.
2001-07-10 14:25:50 +00:00
2001-09-04 13:27:31 +00:00
isalpha2 () # Tests whether *entire string* is alphabetic.
2001-07-10 14:25:50 +00:00
{
[ $# -eq 1 ] || return $FAILURE
case $1 in
*[!a-zA-Z]*|"") return $FAILURE;;
*) return $SUCCESS;;
esac
}
2002-07-22 15:11:51 +00:00
isdigit () # Tests whether *entire string* is numerical.
{ # In other words, tests for integer variable.
[ $# -eq 1 ] || return $FAILURE
case $1 in
2007-04-26 21:13:49 +00:00
*[!0-9]*|"") return $FAILURE;;
*) return $SUCCESS;;
2002-07-22 15:11:51 +00:00
esac
}
2001-07-10 14:25:50 +00:00
2002-07-22 15:11:51 +00:00
check_var () # Front-end to isalpha ().
2001-07-10 14:25:50 +00:00
{
if isalpha "$@"
then
2002-07-22 15:11:51 +00:00
echo "\"$*\" begins with an alpha character."
if isalpha2 "$@"
then # No point in testing if first char is non-alpha.
echo "\"$*\" contains only alpha characters."
else
echo "\"$*\" contains at least one non-alpha character."
fi
else
echo "\"$*\" begins with a non-alpha character."
# Also "non-alpha" if no argument passed.
fi
echo
}
digit_check () # Front-end to isdigit ().
{
if isdigit "$@"
then
echo "\"$*\" contains only digits [0 - 9]."
2001-07-10 14:25:50 +00:00
else
2002-07-22 15:11:51 +00:00
echo "\"$*\" has at least one non-digit character."
2001-07-10 14:25:50 +00:00
fi
2002-07-22 15:11:51 +00:00
echo
2001-07-10 14:25:50 +00:00
}
a=23skidoo
b=H3llo
c=-What?
2002-07-22 15:11:51 +00:00
d=What?
2012-11-27 14:56:18 +00:00
e=$(echo $b) # Command substitution.
2002-07-22 15:11:51 +00:00
f=AbcDef
g=27234
h=27a34
i=27.34
2001-07-10 14:25:50 +00:00
check_var $a
check_var $b
check_var $c
check_var $d
2002-07-22 15:11:51 +00:00
check_var $e
check_var $f
2001-09-04 13:27:31 +00:00
check_var # No argument passed, so what happens?
2002-07-22 15:11:51 +00:00
#
digit_check $g
digit_check $h
digit_check $i
2001-07-10 14:25:50 +00:00
2002-07-22 15:11:51 +00:00
exit 0 # Script improved by S.C.
2001-07-10 14:25:50 +00:00
2002-07-22 15:11:51 +00:00
# Exercise:
# --------
# Write an 'isfloat ()' function that tests for floating point numbers.
# Hint: The function duplicates 'isdigit ()',
#+ but adds a test for a mandatory decimal point.