You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写含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

说明

  1. 大小写兼容:${animal,,}会把用户输入的字符串转成全小写,这样不管用户输入大写、小写还是混合大小写,都能正确匹配对应的分支。如果不需要这个功能,直接用$animal替换$lower_animal即可。
  2. 分支合并优化:我把输出相同的horse|dog和cat|cow合并成了一个分支,减少重复代码,后续维护也更方便。
  3. 变量名修正:把$ animal改成了$animal,确保动物名称能正确显示在输出结果里。

测试一下这个脚本:输入Cat会输出The Cat has 4 legs,输入spider输出The spider has 8 legs,输入snake就会输出The snake has ...,完美符合你的需求!

内容的提问来源于stack exchange,提问作者Justin Siev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:11:29