The final code I ended up using:
# Count characters in a string
function cchar() {
local OPTIND
while getopts "a:" opt; do
case $opt in
a)
echo ${#OPTARG}
return
;;
esac
done
echo "string is ${#1} characters long"
}
$ cchar "foo bar"
string is 7 characters long
$ cchar -a "foo bar"
7
Note: I had to use return
in lieu of exit
, when sourced from .bashrc
, exit
will close the current shell.