shell设计一个函数:能通过输入某人的学号查找其考试成绩
时间: 2023-12-07 14:02:13 浏览: 24
假设考试成绩数据已经存在于一个文本文件中,每行记录包含学号和成绩,用空格分隔。可以先定义一个函数来读取该文件,并将数据存储到一个字典中,以方便查找:
```shell
# 定义函数,读取成绩数据到字典中
function read_scores() {
local scores_file="$1"
declare -A scores
while read line; do
local id=$(echo "$line" | cut -d ' ' -f 1)
local score=$(echo "$line" | cut -d ' ' -f 2)
scores["$id"]=$score
done < "$scores_file"
echo "${scores[@]}"
}
# 示例用法:读取成绩文件 scores.txt 到字典 scores 中
scores=$(read_scores "scores.txt")
```
然后,可以定义另一个函数,根据输入的学号查找对应的成绩:
```shell
# 定义函数,根据学号查找成绩
function find_score() {
local id="$1"
local score="${scores[$id]}"
if [ -n "$score" ]; then
echo "学号 $id 的成绩为 $score 分。"
else
echo "未找到学号为 $id 的成绩。"
fi
}
# 示例用法:查找学号为 123 的成绩
find_score 123
```
这样,就可以通过这两个函数实现根据学号查找成绩的功能了。完整代码如下:
```shell
#!/bin/bash
# 定义函数,读取成绩数据到字典中
function read_scores() {
local scores_file="$1"
declare -A scores
while read line; do
local id=$(echo "$line" | cut -d ' ' -f 1)
local score=$(echo "$line" | cut -d ' ' -f 2)
scores["$id"]=$score
done < "$scores_file"
echo "${scores[@]}"
}
# 定义函数,根据学号查找成绩
function find_score() {
local id="$1"
local score="${scores[$id]}"
if [ -n "$score" ]; then
echo "学号 $id 的成绩为 $score 分。"
else
echo "未找到学号为 $id 的成绩。"
fi
}
# 读取成绩文件 scores.txt 到字典 scores 中
scores=$(read_scores "scores.txt")
# 查找学号为 123 的成绩
find_score 123
```
其中,假设成绩文件 scores.txt 包含以下内容:
```
123 80
456 90
789 85
```
执行脚本后,输出结果为:
```
学号 123 的成绩为 80 分。
```