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

如何编写Bash脚本maxmin.sh 获取5个输入数字的最大值与最小值

maxmin.sh 编写教程

完整脚本代码

#!/bin/bash

# 校验输入参数数量是否为5
if [ $# -ne 5 ]; then
    echo "错误:请输入恰好5个数字作为参数"
    exit 1
fi

# 将输入参数存入数组
nums=("$@")

# 初始化最大值和最小值为第一个输入值
max=${nums[0]}
min=${nums[0]}

# 遍历所有数字更新最值
for num in "${nums[@]}"; do
    # 比较更新最大值
    if [ "$num" -gt "$max" ]; then
        max=$num
    fi
    # 比较更新最小值
    if [ "$num" -lt "$min" ]; then
        min=$num
    fi
done

# 按要求格式输出结果
echo "Highest number is $max and Lowest number is $min"

使用方法

  • 给脚本添加执行权限:chmod +x maxmin.sh
  • 运行脚本传入5个数字参数,示例:
./maxmin.sh 3 15 -1 99 22
  • 输出结果和预期一致:

Highest number is 99 and Lowest number is -1

逻辑说明

  • 首先做参数校验,避免参数数量不对导致运行异常
  • 遍历所有输入值动态更新最值,支持正负数的比较判断
  • 输出格式严格匹配要求,不需要额外调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:24:05