1. 程式人生 > >2018-05-29 Linux學習

2018-05-29 Linux學習

Linux學習

20.1 Shell腳本介紹

shell是什麽

shell是一種腳本語言  aming_linux  blog.lishiming.net
可以使用邏輯判斷、循環等語法
可以自定義函數
shell是系統命令的集合
shell腳本可以實現自動化運維,能大大增加我們的運維效率

20.2 Shell腳本結構和執行

開頭需要加#!/bin/bash
以#開頭的行作為解釋說明
腳本的名字以.sh結尾,用於區分這是一個shell腳本
執行方法有兩種
chmod +x 1.sh; ./1.sh
bash 1.sh
查看腳本執行過程 bash -x 1.sh
查看腳本是否語法錯誤  bash -n 1.sh

20.3 date命令用法

date??+%Y-%m-%d, date +%y-%m-%d 年月日
date??+%H:%M:%S = date +%T 時間
date +%s??時間戳
date -d @1504620492
date -d "+1day"  一天後
date -d "-1 day"  一天前
date -d "-1 month" 一月前
date -d "-1 min"  一分鐘前
date +%w, date +%W 星期

操作過程

[root@linux-01 ~]# date
2018年 04月 22日 星期日 21:12:09 CST
[root@linux-01 ~]# date +%Y
2018
[root@linux-01 ~]# date +%y
18
[root@linux-01 ~]# date +%m
04
[root@linux-01 ~]# date +%M
12
[root@linux-01 ~]# date +%d
22
[root@linux-01 ~]# date +%D
04/22/18
[root@linux-01 ~]# date +%Y%m%d
20180422
[root@linux-01 ~]# date +%F
2018-04-22

[root@linux-01 ~]# date +%H
21
[root@linux-01 ~]# date +%s
1524402829
[root@linux-01 ~]# date +%S
54

[root@linux-01 ~]# date +%T
21:15:14
[root@linux-01 ~]# date +%h
4月
[root@linux-01 ~]# date +%w
0
[root@linux-01 ~]# date +%W
16

[root@linux-01 ~]# 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

[root@linux-01 ~]# LANG=en_US
[root@linux-01 ~]# date
Sun Apr 22 21:25:46 CST 2018

[root@linux-01 ~]# date -d "-1 day"
Sat Apr 21 21:26:18 CST 2018
[root@linux-01 ~]# date -d "-1 day" +%F
2018-04-21
[root@linux-01 ~]# date -d "-1 month"
Thu Mar 22 21:26:36 CST 2018
[root@linux-01 ~]# date -d "-1 year"
Sat Apr 22 21:27:56 CST 2017
[root@linux-01 ~]# date -d "-1 hour"
Sun Apr 22 20:28:05 CST 2018
[root@linux-01 ~]# date -d "-1 hour" +%F
2018-04-22
[root@linux-01 ~]# date -d "-1 hour" +%T
20:29:01

[root@linux-01 ~]# date +%s
1524403788
[root@linux-01 ~]# date -d @1524403788
Sun Apr 22 21:29:48 CST 2018

[root@linux-01 ~]# date +%s -d "2018-04-22 21:29:48"
1524403788

20.4 Shell腳本中的變量

當腳本中使用某個字符串較頻繁並且字符串長度很長時就應該使用變量代替
使用條件語句時,常使用變量? ? 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] 

2018-05-29 Linux學習