20.1 Introduction to Shell Scripts 20.2 Shell Script Structure and Execution 20.3 Date Command Usage 20.4 Variables in Shell Scripts

20.1 Introduction to shell scripts

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

20.2 Shell script structure and execution

shell脚本结构和执行方法

开头需要加#!/bin/bash
以#开头的行作为解释说明
脚本的名字以.sh结尾,用于区分这是一个shell脚本
执行方法有两种
chmod +x 1.sh; ./1.sh
bash 1.sh  / sh 1.sh
查看脚本执行过程 bash -x 1.sh
查看脚本是否语法错误  bash -n 1.sh

20.3 date command usage

date  +%F %T
date  +%Y-%m-%d, date +%y-%m-%d 年月日  = +%F
date  +%H:%M:%S = date +%T 时间

date +%s  时间戳  距离1970年0点0分多少秒
date -d @1504620492
date -d "+1day"  一天后
date -d "-1 day"  一天前
date -d "-1 month" 一月前
date -d "-1 hour"  一小时前
date -d "-1 min"  一分钟前
date +%w  星期几
date +%W 今年的第几周

20.4 Variables in shell scripts

当脚本中使用某个字符串较频繁并且字符串长度很长时就应该使用变量代替
使用条件语句时,常使用变量    if [ $a -gt 1 ]; then ... ; fi
引用某个命令的结果时,用变量替代   n=`wc -l 1.txt`
写和用户交互的脚本时,变量也是必不可少的  read -p "Input a number: " n; echo $n   如果没写这个n,可以直接使用$REPLY
内置变量 $0, $1, $2…    $0表示脚本本身,$1 第一个参数,$2 第二个 ....       $#表示参数个数
数学运算a=1;b=2; c=$(($a+$b))或者$[$a+$b]


shell 单括号运算符号:
a=$(date);
等同于:a=`date`;
 
双括号运算符:
a=$((1+2));
echo $a;
等同于:
a=`expr 1 + 2`

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521138&siteId=291194637