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

如何编写Bash函数根据指定数字输出对应数量的echo内容?

简洁实现Bash数字对应文本输出函数

核心思路

把1到50对应的英文文本预存在数组中,根据输入的数字循环输出数组的前N个元素。这种方式替代了冗长的硬编码判断,扩展和维护都更便捷。

完整代码实现

print_num_text() {
    # 存储1到50对应的英文表述
    local num_texts=(
        "one" "two" "three" "four" "five"
        "six" "seven" "eight" "nine" "ten"
        "eleven" "twelve" "thirteen" "fourteen" "fifteen"
        "sixteen" "seventeen" "eighteen" "nineteen" "twenty"
        "twenty-one" "twenty-two" "twenty-three" "twenty-four" "twenty-five"
        "twenty-six" "twenty-seven" "twenty-eight" "twenty-nine" "thirty"
        "thirty-one" "thirty-two" "thirty-three" "thirty-four" "thirty-five"
        "thirty-six" "thirty-seven" "thirty-eight" "thirty-nine" "forty"
        "forty-one" "forty-two" "forty-three" "forty-four" "forty-five"
        "forty-six" "forty-seven" "forty-eight" "forty-nine" "fifty"
    )
    local input=$1

    # 验证输入合法性
    if [[ ! $input =~ ^[0-9]+$ ]] || (( input < 1 || input > 50 )); then
        echo "Error: 请输入1到50之间的整数"
        return 1
    fi

    # 循环输出对应数量的文本行
    for ((i=0; i<input; i++)); do
        echo "${num_texts[$i]}"
    done
}

使用示例

  • 执行 print_num_text 3,输出:
    one
    two
    three
    
  • 执行 print_num_text 10,输出:
    one
    two
    three
    four
    five
    six
    seven
    eight
    nine
    ten
    

方案优势

  • 简洁易维护:扩展数字范围时,只需在数组末尾追加对应的文本即可,无需修改逻辑代码。
  • 输入校验:加入了对输入格式和范围的检查,避免非法输入导致的异常。
  • 性能高效:数组访问是O(1)操作,循环输出的效率远高于大量条件判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:36:31