Debian Codegraph @

isalpha.sh

raw symbols SCIP
1 #!/bin/bash
2 # isalpha.sh: Using a "case" structure to filter a string.
3
4 SUCCESS=0
5 FAILURE=1 # Was FAILURE=-1,
6 #+ but Bash no longer allows negative return value.
7
8 isalpha () # Tests whether *first character* of input string is alphabetic.
9 {
10 if [ -z "$1" ] # No argument passed?
11 then
12 return $FAILURE
13 fi
14
15 case "$1" in
16 [a-zA-Z]*) return $SUCCESS;; # Begins with a letter?
17 * ) return $FAILURE;;
18 esac
19 } # Compare this with "isalpha ()" function in C.
20
21
22 isalpha2 () # Tests whether *entire string* is alphabetic.
23 {
24 [ $# -eq 1 ] || return $FAILURE
25
26 case $1 in
27 *[!a-zA-Z]*|"") return $FAILURE;;
28 *) return $SUCCESS;;
29 esac
30 }
31
32 isdigit () # Tests whether *entire string* is numerical.
33 { # In other words, tests for integer variable.
34 [ $# -eq 1 ] || return $FAILURE
35
36 case $1 in
37 *[!0-9]*|"") return $FAILURE;;
38 *) return $SUCCESS;;
39 esac
40 }
41
42
43
44 check_var () # Front-end to isalpha ().
45 {
46 if isalpha "$@"
47 then
48 echo "\"$*\" begins with an alpha character."
49 if isalpha2 "$@"
50 then # No point in testing if first char is non-alpha.
51 echo "\"$*\" contains only alpha characters."
52 else
53 echo "\"$*\" contains at least one non-alpha character."
54 fi
55 else
56 echo "\"$*\" begins with a non-alpha character."
57 # Also "non-alpha" if no argument passed.
58 fi
59
60 echo
61
62 }
63
64 digit_check () # Front-end to isdigit ().
65 {
66 if isdigit "$@"
67 then
68 echo "\"$*\" contains only digits [0 - 9]."
69 else
70 echo "\"$*\" has at least one non-digit character."
71 fi
72
73 echo
74
75 }
76
77 a=23skidoo
78 b=H3llo
79 c=-What?
80 d=What?
81 e=$(echo $b) # Command substitution.
82 f=AbcDef
83 g=27234
84 h=27a34
85 i=27.34
86
87 check_var $a
88 check_var $b
89 check_var $c
90 check_var $d
91 check_var $e
92 check_var $f
93 check_var # No argument passed, so what happens?
94 #
95 digit_check $g
96 digit_check $h
97 digit_check $i
98
99
100 exit 0 # Script improved by S.C.
101
102 # Exercise:
103 # --------
104 # Write an 'isfloat ()' function that tests for floating point numbers.
105 # Hint: The function duplicates 'isdigit ()',
106 #+ but adds a test for a mandatory decimal point.