1 案例1:Shell脚本的编写及测试
1.1 问题
本例要求两个简单的Shell脚本程序,任务目标如下:
- 编写一个面世问候 /root/helloworld.sh 脚本,执行后显示出一段话“Hello World!!”
- 编写一个能输出系统信息的 /root/sysinfo 脚本,执行后依次输出当前红帽系统的版本信息、当前使用的内核版本、当前系统的主机名
1.2 方案
规范Shell脚本的一般组成:
- #! 环境声明(Sha-Bang)
- # 注释文本
- 可执行代码
1.3 步骤
实现此案例需要按照如下步骤进行。
步骤一:编写helloworld.sh问候脚本
1)编写脚本代码
- [root@server0 ~]# vim /root/helloworld.sh
- #!/bin/bash
- echo "Hello World !!"
2)添加x执行权限
- [root@server0 ~]# chmod +x /root/helloworld.sh
3)运行脚本测试
- [root@server0 ~]# /root/helloworld.sh
- Hello World !!
步骤二:编写sysinfo系统信息报告脚本
1)编写脚本代码
- [root@server0 ~]# vim /root/sysinfo
- #!/bin/bash
- cat /etc/redhat-release
- uname -r
- hostname
2)添加x执行权限
- [root@server0 ~]# chmod +x /root/sysinfo
3)运行脚本测试
- [root@server0 ~]# /root/sysinfo
- Red Hat Enterprise Linux Server release 7.0 (Maipo)
- 3.10.0-123.el7.x86_64
- server0.example.com
2 案例2:重定向输出的应用
2.1 问题
本例要求编写一个脚本 /root/out.sh,功能特性如下:
- 执行此脚本显示 I love study !!
- 执行 /root/out.sh 2> err.log 应该没有显示,但是查看 err.log 文件的内容为 I love study !!
2.2 方案
屏幕输出文本的类别:
- 标准输出(1):命令行执行正常的显示结果
- 标准错误(2):命令行执行出错或异常时的显示结果
将屏幕显示信息保存到文件:
- cmd > file 、 cmd >> file
- cmd 2> file 、 cmd 2>> file
- cmd &> file 、cmd 2> file 1>&2
使用1>&2或>&2操作,可以将命令行的标准输出编程标准错误。
2.3 步骤
实现此案例需要按照如下步骤进行。
步骤:编写out.sh输出测试脚本
1)编写脚本代码