MST

星途 面试题库

面试题:Bash数组的复杂遍历与操作

假设有一个Bash数组,其中存储了一些数字(例如:(10 20 30 40 50))。编写脚本实现以下功能:1. 遍历数组,找出数组中的最大值和最小值;2. 将数组元素按从小到大的顺序排序并输出新数组。
12.2万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 定义数组
nums=(10 20 30 40 50)

# 初始化最大值和最小值为数组第一个元素
max=${nums[0]}
min=${nums[0]}

# 遍历数组找最大值和最小值
for num in ${nums[@]}; do
    if ((num > max)); then
        max=$num
    fi
    if ((num < min)); then
        min=$num
    fi
done

echo "最大值: $max"
echo "最小值: $min"

# 对数组进行排序并输出
sorted_nums=($(printf '%d\n' "${nums[@]}" | sort -n))
echo "排序后的数组: ${sorted_nums[@]}"