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

shell脚本介绍、shell脚本结构和执行、date命令用法、shell脚本中的变量

2017-11-28 10:03 926 查看

shell脚本介绍

shell是一种脚本语言
可以使用逻辑判断、循环等语法
可自定义函数
shell是系统命令的集合
shell脚本可以实现自动化运维,能大大增加我们的运维效率

shell脚本结构和执行

结构
开头需要“#!/bin/bash”
脚本内容中以#开头的行作为解释说明
编写脚本时备注:作者、时间、功能等信息,方便之后查看
脚本的名字用“.sh”结尾,用于区分这是一个shell脚本

执行方法
给脚本添加执行权限“chmod a+x test.sh”,然后直接执行该脚本“./test.sh”
bash test.sh;sh test.sh

sh参数
-x:sh -x test.sh 查看脚本执行过程
-n:sh -n test.sh 查看脚本是否存在语法错误

date命令用法

date命令用于显示或设置系统时间与日期。
-d<字符串>:显示字符串所指的日期与时间。字符串前后必须加上双引号;
-s<字符串>:根据字符串来设置日期与时间。字符串前后必须加上双引号;

1、显示当前时间
[root@centos7 ~]# date
Tue Nov 28 09:44:26 CST 2017

2、显示日历
[root@centos7 ~]# cal
November 2017
Su Mo Tu We Th Fr Sa
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

3、date +%Y(%y):以四位(两位)数字格式显示年份
[root@centos7 ~]# date +%Y
2017
[root@centos7 ~]# date +%y
17

4、显示年、月、日、小时、分钟、秒、第几周
[root@centos7 ~]# date "+%Y-%m-%d %H:%M:%S %w"
2017-11-28 09:46:39 2

5、显示年月日
[root@centos7 ~]# date +%F
2017-11-28

6、显示完整时间
[root@centos7 ~]# date +%T
09:48:34

7、使用前1天
[root@centos7 ~]# date -d "-1 day" +%d
27
[root@centos7 ~]# date -d "-2 day" +%d
26

8、手动设置时间
[root@centos7 ~]# date -s '2017-11-28 09:50:30'
Tue Nov 28 09:50:30 CST 2017

9、同步网络时间:ntpdate命令
yum install -y ntp
ntpdate ntp.ubuntu.com

shell脚本中的变量

1、普通变量
[root@centos7 shell]# vi test.sh

#!/bin/bash
path_dir=/tmp/test
[ -d $path_dir ]&&{
echo "path_dir" 存在
exit
}
2、内置变量
$0:表示脚本本身
$1:第一个参数
$2:第二个参数
$#:表示参数的个数

[root@centos7 shell]# vi test.sh

#!/bin/bash
a=$1
b=$2
sum=$[$a+$b]
echo $sum

3、用户交互模式read -p
-t:限制时间
[root@centos7 shell]# vi test.sh

#!/bin/bash
read -t 3 -p "Please input a number:" x
[ -z $x ]&& {
echo '输入空值,exit'
exit 2
}
read -t 3 -p "Please input a number:" y
sum=$[$x+$y]
echo "$x+$y=$sum"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell脚本
相关文章推荐