shell简介:shell是一种脚本语言,可以使用逻辑判断、循环等语法,可以自定义函数,是系统命令的集合
文章目录
shell脚本结构和执行方法
1.shell脚本开头需要加#!/bin/bash
2.以#开头的行作为注释
3.脚本的名字以.sh结尾,用于区分这是一个shell脚本
4.执行方法有两种:
1)bash test.sh
2)./test.sh
#第二种执行方式需要有执行权限(chmod +x test.sh)
5.查看脚本执行过程:bash -x test.sh
6.查看脚本是否语法错误:bash -n test.sh
#bash可以使用sh命令代替(在/usr/bin目录下,sh是bash的软连接文件)
date命令的用法
年月日:
[root@linux ~]# date
2019年 11月 19日 星期二 16:20:04 CST
[root@linux ~]# date +%Y-%m-%d
2019-11-19
[root@linux ~]# date +%Y
2019
[root@linux ~]# date +%m
11
[root@linux ~]# date +%d
19
[root@linux ~]# date +%y #表示2019年,忽略20
19
[root@linux ~]# date +%F
2019-11-19
时分秒:
[root@linux ~]# date
2019年 11月 19日 星期二 16:27:46 CST
[root@linux ~]# date +%H-%M-%S
16-28-04
[root@linux ~]# date +%T
16:28:09
周:
[root@linux ~]# date +%w #表示星期几
2
[root@linux ~]# date +%W 表示今年的第多少周
46
时间戳:
[root@linux ~]# date +%s #表示1970年1月1日到现在
1574152197
[root@linux ~]# date -d @1534150197 #倒推时间戳
2018年 08月 13日 星期一 16:49:57 CST
补充:
[root@linux ~]# date
2019年 11月 19日 星期二 16:34:37 CST
[root@linux ~]# date -d "+3day" #三天后
2019年 11月 22日 星期五 16:34:45 CST
[root@linux ~]# date -d "-3day" +%F #三天前
2019-11-16
[root@linux ~]# date -d "-3 month" +%F #三个月前
2019-08-19
[root@linux ~]# date -d "-30 min" +%F_%T #30分钟前
2019-11-19_16:06:16
shell中变量的用法
使用变量的情况:
1.当脚本中使用某个字符串较频繁并且字符串长度很长时就应该使用变量代替
2.使用条件语句时,常使用变量判断大小 if [ $a -gt 1 ]; then … ; fi
3.引用某个命令的结果时,用变量替代 n=wc -l test.txt
4.写和用户交互的脚本时,变量也是必不可少的 :
[root@linux ~]# read -p "input a number:" n
input a number:15
[root@linux ~]# echo $n
15
如果没有自定义变量,可以使用内置变量$REPLY:
[root@linux ~]# read -p "input a number:"
input a number:9
[root@linux ~]# echo $REPLY
9
5.内置变量
$1,$2,$3,$# ($1 第一个参数,$2 第二个参数,$#表示参数的和):
#!/bin/bash
echo "第一个参数是$1"
echo "第二个参数是$2"
echo "一共有$#个参数"
结果示例:
[root@linux ~]# ./test.sh a b c
第一个参数是a
第二个参数是b
一共有3个参数
$0表示脚本名(根据执行脚本方式的不同结果不同):
#!/bin/bash
echo "\$0是:$0"
结果示例:
[root@linux ~]# /root/test.sh
$0是:/root/test.sh
[root@linux ~]# ./test.sh
$0是:./test.sh
[root@linux ~]# sh test.sh
$0是:test.sh
6.数学运算a=1;b=2; c=$(($a+$b))或者$[$a+$b]:
[root@linux ~]# a=1
[root@linux ~]# b=2
[root@linux ~]# c=$(($a+$b))
[root@linux ~]# echo $c
3
[root@linux ~]# d=$[$a+$b]
[root@linux ~]# echo $d
3
shell逻辑判断语法
格式1:if 条件 ; then 语句; fi
#!/bin/bash
read -p "input a number:" n
if [ $n -gt 5 ]
then
echo "1"
fi
格式2:if 条件; then 语句; else 语句; fi
#!/bin/bash
read -p "input a number:" n
if [ $n -gt 5 ]
then
echo "1"
else
echo "2"
fi
格式3:if …; then … ;elif …; then …; else …; fi
#!/bin/bash
read -p "input a number:" n
if [ $n -gt 90 ]
then
echo "A"
elif [ $n -gt 70 ]
then
echo "B"
else
echo "C"
fi
格式4:if 中嵌套 if
#!/bin/bash
read -p "input a number:" n
if [ $n -gt 70 ]
then
echo "OK"
if [