本案例要求编写test.sh脚本,相关要求如下:
• 能使用redhat、fedora控制参数
• 控制参数通过位置变量$1传入
• 当用户输入redhat参数,脚本返回fedora
• 当用户输入fedora参数,脚本返回redhat
• 当用户输入其他参数,则提示错误信息
case分支属于匹配执行的方式,它针对指定的变量预先设置一个可能的取值,判断该变量的实际取值是否与预设的某一个值相匹配,如果匹配上了,就执行相应的一组操作,如果没有任何值能够匹配,就执行预先设置的默认操作。
case分支的语法结构如下所示:
1. case 变量 in
2. 模式1)
3. 命令序列1 ;;
4. 模式2)
5. 命令序列2 ;;
6. .. ..
7. *)
8. 默认命令序列
9. esac
步骤一:编写脚本文件
脚本编写参考如下:
1. [root@dyy ~]# vim test.sh
2. #!/bin/bash
3. case $1 in
4. redhat)
5. echo "fedora";;
6. fedora)
7. echo "redhat";;
8. *) //默认输出脚本用法
9. echo "用法: $0 {redhat|fedora}"
10. esac
11.
12. [root@dyy ~]# chmod +x test.sh
步骤二:验证、测试脚本
未提供参数,或提供的参数无法识别时,提示正确用法:
1. [root@dyy ~]# ./test.sh
用法: ./test.sh {redhat|fedora}
确认脚本可以响应redhat控制参数:
1. [root@dyy ~]# ./test.sh redhat
2. fedora
确认脚本可以响应fedora控制参数:
1. [root@dyy ~]# ./test.sh fedora
2. redhat