如何编写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
相关产品推荐
相关产品推荐

