Files
fzu-product/3.编程思维体系构建/3.Y.7linux小任务.md
2023-11-02 14:39:35 +08:00

127 lines
4.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# linux 自测
1. 本课程需要使用类 Unix shell例如 Bash 或 ZSH。如果您在 Linux 或者 MacOS 上面完成本课程的练习,则不需要做任何特殊的操作。如果您使用的是 Windows则您不应该使用 cmd 或是 Powershell您可以使用<u>Windows Subsystem for Linux</u>或者是 Linux 虚拟机。使用 `echo $SHELL` 命令可以查看您的 shell 是否满足要求。如果打印结果为 `/bin/bash``/usr/bin/zsh` 则是可以的。
2.`/tmp` 下新建一个名为 `missing` 的文件夹。
3.`man` 查看程序 `touch` 的使用手册。
4.`touch``missing` 文件夹中新建一个叫 `semester` 的文件。
5. 将以下内容一行一行地写入 `semester` 文件:
```bash
#!/bin/sh
curl --head --silent https://missing.csail.mit.edu
```
第一行可能有点棘手, `#` 在 Bash 中表示注释,而 `!` 即使被双引号(`"`)包裹也具有特殊的含义。单引号(`'`)则不一样,此处利用这一点解决输入问题。更多信息请参考 <u>Bash quoting 手册</u>
1. 尝试执行这个文件。例如,将该脚本的路径(`./semester`)输入到您的 shell 中并回车。如果程序无法执行,请使用 `ls` 命令来获取信息并理解其不能执行的原因。
2. 查看 `chmod` 的手册 (例如,使用 `man chmod` 命令)
3. 使用 `chmod` 命令改变权限,使 `./semester` 能够成功执行,不要使用 `sh semester` 来执行该程序。您的 shell 是如何知晓这个文件需要使用 `sh` 来解析呢?更多信息请参考:<u>shebang</u>
4. 使用 `|``>` ,将 `semester` 文件输出的最后更改日期信息,写入主目录下的 `last-modified.txt` 的文件中
5. 写一段命令来从 `/sys` 中获取笔记本的电量信息,或者台式机 CPU 的温度
6. 使用 shell 编程写一个类似脚本的图书管理系统,包含增删改查四个功能
当然,可能会有点困难我在这里附上一段参考代码
```shell
#! /usr/bin/env bash
initialization()
{
echo -n "| " ;echo "1:添加图书"
echo -n "| " ;echo "2:删除图书"
echo -n "| " ;echo "3:显示馆藏图书"
echo -n "| " ;echo "4:查找图书"
echo -n "| " ;echo "5:退出系统"
mainmenu
}
mainmenu()
{
read operation
case $operation in
1)
addbook ;;
2)
delbook ;;
3)
listbooks ;;
4)
search ;;
5)
exit ;;
*)
"无效操作,请重试。"
initialization ;;
esac
}
#直接在文件夹内添加书(所以没有 书单.txt若没有就find遍历系统匹配并加入
#不考虑系统中多个匹配结果的情况
addbook()
{
echo "添加图书"
echo "-------------------------"
read -p "输入添加的书名" bookname
if [[ -f ~/Desktop/bookregister/$bookname ]] ;
then
echo "已经存在这本书。"
return
else
find ~ -name $bookname -exec mv {} ~/Desktop/bookregister \;
if [[ -f ~/Desktop/bookregister/$bookname ]] ;
then
echo "匹配成功,已加入书单。"
else
read -p "未找到这本书,手动输入链接从网上下载?[y/n]" download
if [[ $download = 'y' ]] ;
then
read -p "请输入链接。" url
curl ${url} -o $bookname
find ~ -name $bookname -exec mv {} ~/Desktop/bookregister \;
fi
fi
fi
}
delbook()
{
echo "删除图书"
echo "-------------------------"
read -p "输入删除的书名" bookname
if [[ ! -f ~/Desktop/bookregister/$bookname ]] ;
then
echo "查无此书。"
return
else
read -p "输入 delete 以确认。" delete
if [[ $delete = delete ]];
then
rm ~/Desktop/bookregister/$bookname
echo "删除完毕。"
fi
fi
}
#因为脚本图书放在一起,所以脚本自身也会显示(不要在意这些细节)
listbooks()
{
ls ~/Desktop/bookregister
}
#若找到直接用less打开
search()
{
echo "查找图书"
echo "-------------------------"
read -p "输入查找的书名" bookname
if [[ -f ~/Desktop/bookregister/$bookname ]] ;
then
less ~/Desktop/bookregister/$bookname
else
echo "查无此书。"
fi
}
```