编写含case语句的BASH脚本:根据输入动物返回对应腿数
修正你的动物腿数查询BASH脚本
Hey Justin! Let's get your animal leg-count script working smoothly. I spotted a tiny typo in your code that would break one of the cases, plus we can make a couple of small improvements for better usability.
原脚本的问题
- 在匹配
cat|cow的分支里,你写了$ animal(多了个空格),这会导致输出变成The has 4 legs(动物名称没被正确替换),应该改成$animal。 - 默认分支的语法可以更统一,把
;;和echo放在同一行(保持格式一致更易读)。 - 可选优化:让输入不区分大小写,比如把输入转成小写,这样用户输入
Spider、SPIDER都能正确匹配。
修正后的脚本
#!/bin/bash echo -n "Enter an animal: " read animal # 转成小写,实现不区分大小写匹配(可选,不需要的话可以删掉这行,直接用$animal) lower_animal=${animal,,} case $lower_animal in spider|octopus) echo "The $animal has 8 legs";; horse|dog|cat|cow) echo "The $animal has 4 legs";; # 把同腿数的动物合并,代码更简洁 kangaroo|person) echo "The $animal has 2 legs";; *) echo "The $animal has ...";; esac
说明
- 大小写兼容:
${animal,,}会把用户输入的字符串转成全小写,这样不管用户输入大写、小写还是混合大小写,都能正确匹配对应的分支。如果不需要这个功能,直接用$animal替换$lower_animal即可。 - 分支合并优化:我把输出相同的
horse|dog和cat|cow合并成了一个分支,减少重复代码,后续维护也更方便。 - 变量名修正:把
$ animal改成了$animal,确保动物名称能正确显示在输出结果里。
测试一下这个脚本:输入Cat会输出The Cat has 4 legs,输入spider输出The spider has 8 legs,输入snake就会输出The snake has ...,完美符合你的需求!
内容的提问来源于stack exchange,提问作者Justin Siev
相关产品推荐
相关产品推荐

