I'm trying to create a simple function on macOS Sierra that counts the characters in a string. This works fine (added to my bashrc
file):
function cchar() {
str=$1
len=${#str}
echo "string is $len char long"
}
$ cchar "foo"
string is 3 char long
I'm trying to expand it with a -a
option, so I added this to my function (and commented the rest out for testing):
while getopts "a:" opt; do
case $opt in
a)
echo "-a param: $OPTARG" >&2
;;
esac
done
After some testing while writing this, I've noticed everytime I run cchar -a "test"
, I have to run it without options (cchar
) otherwise the next time I run it with the -a
option, it doesn't recognise the option.
$ cchar
$ cchar -a "foo"
-a param: foo
$ cchar -a "foo"
$ cchar
$ cchar -a "foo"
-a param: foo