Linux Shell脚本_设置时区并同步时间

① 脚本编写

vim autoSyncTime.sh

脚本内容:

ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
if ! crontab -l |grep ntpdate &>/dev/null ; then
    (echo "* 1 * * * ntpdate ntp1.aliyun.com >/dev/null 2>&1";hwclock -w;crontab -l) |crontab 
fi

保存退出:wq
② 运行脚本

chmod u+x autoSyncTime.sh
./AutoSyncTime.sh
或者
bash autoSyncTime.sh

③ 脚本内容简述
查看系统信息

[root@ly-01 ~]# cat /etc/redhat-release 
CentOS Linux release 7.6.1810 (Core)
#查看当前默认时区 UTC
[root@ly-01 ~]# date
Mon Feb 24 08:59:26 CST 2020

#修改时区为亚洲上海时区
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

#安装Linux系统时间同步服务软件:ntpdate 如果已安装,则跳过此步骤
[root@localhost ~]# yum -y install ntpdate

#Linux系统时间同步 
#让当前服务器同步到网络时间,从而来更新当前服务器的时间。以下命令表示的是让当前服务器时间同步到ntp1.aliyun.com
[root@localhost ~]# ntpdate ntp1.aliyun.com
#Linux硬件时间同步:修改服务器硬件时间映射到我们的系统时间,也可以说系统时间同步到硬件时间,防止系统重启后时间还原。
hwclock -w

#定时同步,牵扯到定时任务
#查看当前用户的定时任务
[root@ly-01 ~]# crontab -l
#给当前用户添加定时任务
[root@ly-01 ~]# crontab -e

#同步时间规则,每天1点同步一次
* 1 * * *

#将错误追加为空 >前面下具体执行的命令
>/dev/null 2>&1

#判断现定时任务列表中是否有次定时任务,有,则跳过下面设置定时任务的逻辑
if ! crontab -l |grep ntpdate &>/dev/null ;
#下面这是一组命令 可直接执行
(echo "* 1 * * * ntpdate ntp1.aliyun.com >/dev/null 2>&1";hwclock -w;crontab -l) |crontab

在这里插入图片描述

发布了976 篇原创文章 · 获赞 151 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/weixin_40816738/article/details/105366737