我有一个Bash脚本,根据变量的值执行操作。 case语句的一般语法是:
- case ${command} in
- start) do_start ;;
- stop) do_stop ;;
- config) do_config ;;
- *) do_help ;;
- esac
如果没有提供命令,我想执行默认例程,如果命令无法识别,则执行do_help。我试图省略case值这样:
- case ${command} in
- ) do_default ;;
- ...
- *) do_help ;;
- esac
结果是可预测的,我想:
- Syntax error near unexpected token `)'
然后我试着用正规表达式使用我最好的镜头:
- case ${command} in
- ^$) do_default ;;
- ...
- *) do_help ;;
- esac
有了这个,一个空的$ {command}落到了* case。
我想做不可能的事吗?
case语句使用globs,而不是regexes,并坚持使用完全匹配。
所以空字符串像往常一样被写为“”或“’:
- case "$command" in
- "") do_empty ;;
- something) do_something ;;
- prefix*) do_prefix ;;
- *) do_other ;;
- esac