您的位置:首页 > 运维架构 > Shell

Shell脚本的介绍,结构,执行,date用法

2018-01-20 10:53 381 查看

Shell脚本介绍

Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁。Shell 既是一种命令语言,又是一种程序设计语言。

shell是一种脚本语言;

可以使用逻辑判断、循环等语法;

可自定义函数;

shell是系统命令的集合;

shell脚本可以实现自动化运维,能大大增加我们的运维效率;

Shell脚本结构和执行

结构

开头需要“#!/bin/bash“;

脚本内容中以#开头的行作为解释说明;

编写脚本时备注:作者、时间、功能等信息,方便之后查看;

脚本的名字用“.sh”结尾,用于区分这是一个shell脚本;

执行方法

1、作为可执行程序:给脚本添加执行权限“chmod a+x test.sh”,然后直接执行该脚本“./test.sh”;
2,作为解释器参数:使用sh执行  # sh test.sh;


sh参数

-x:sh -x test.sh 查看脚本执行过程

-n:sh -n test.sh 检测语法错误

date命令用法

命令描述:

date命令用于显示或设置系统时间与日期。

命令选项:

-d :显示字符串指定的日期与时间(字符串前后必须加上双引号)

-s:根据字符串来设置时间与日期(字符串前后必须加双引号)

命令示例

[root@dl-001 shell]# date       //查看当前时间
2018年 01月 20日 星期六 10:10:25 CST
[root@dl-001 shell]# cal            //查看系统日期
一月 2018
日 一 二 三 四 五 六
1  2  3  4  5  6
7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

[root@dl-001 shell]# date +%Y           //查看当前年份(四位显示)
2018
[root@dl-001 shell]# date +%y           //查看当前年份(简化显示)
18
[root@dl-001 shell]# date "+%Y-%m-%d %H:%M:%S %w"   //查看当前 年 月 日  时 分 秒 星期
2018-01-20 10:11:15 6
[root@dl-001 shell]# date +%F       //查看当前完整的年月日
2018-01-20
[root@dl-001 shell]# date +%W           //查看当前时间是一年的第几周
03
[root@dl-001 shell]# date +%T           //查看当前时间是几点
10:11:39
[root@dl-001 shell]# date +%s           //查看时间戳(显示从1970年1月1日00:00:00到目前经历的秒数)
1516414309

//时间戳的换算
[root@dl-001 shell]# date +%s -d  "2018-01-20 22:00:00"
1516456800
[root@dl-001 shell]# date -d @1516456800
2018年 01月 20日 星期六 22:00:00 CST

//打印指定日期和时间
[root@dl-001 shell]# date -d "-2 day" +%d
18
[root@dl-001 shell]# date -d "-1 year -3 month -1 day" +%Y-%m-%d
2016-10-19

//手动设置当前时间
[root@dl-001 shell]# date -s "2017-5-20 12:00:00"
2017年 05月 20日 星期六 12:00:00 CST
[root@dl-001 shell]# date
2017年 05月 20日 星期六 12:00:03 CST

//同步网络时间
[root@dl-001 shell]# yum install -y ntp
[root@dl-001 shell]# ntpdate ntp.ubuntu.com
20 Jan 10:47:42 ntpdate[8615]: step time server 91.189.89.198 offset 21163558.201100 sec
[root@dl-001 shell]# date
2018年 01月 20日 星期六 10:47:45 CST
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell
相关文章推荐