我正在尝试在macOS Sierra上创建一个简单的函数来计算字符串中的字符.这工作正常(添加到我的bashrc文件):
function cchar() {
str=$1
len=${#str}
echo "string is $len char long"
}
$ cchar "foo"
string is 3 char long
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用一个-a选项扩展它,所以我将其添加到我的函数中(并将其余部分注释用于测试):
while getopts "a:" opt; do
case $opt in
a)
echo "-a param: $OPTARG" >&2
;;
esac
done
Run Code Online (Sandbox Code Playgroud)
在写这篇文章的一些测试之后,我注意到每次运行时cchar -a "test",我都必须运行它而没有选项(cchar)否则下次我使用该-a选项运行它时,它无法识别该选项.
$ cchar
$ cchar -a "foo"
-a param: foo
$ cchar -a "foo"
$ cchar
$ cchar -a "foo"
-a param: foo
Run Code Online (Sandbox Code Playgroud)