1. 程式人生 > 其它 >|NO.Z.00038|——————————|CloudNative|——|CI/CD&Jenkins_pipeline操作.V12|-------------------------------------------|Jenkins_pipeline外掛|

|NO.Z.00038|——————————|CloudNative|——|CI/CD&Jenkins_pipeline操作.V12|-------------------------------------------|Jenkins_pipeline外掛|

shell 指令碼

介紹

shell 是一個命令列直譯器,它接收應用程式/使用者命令,然後呼叫作業系統核心。shell 還是一個功能強大的程式語言,易編寫、易除錯、靈活性強。

第一行的作用

#!/bin/bash

Shebang 在計算機程式中,shebang 指的是出現在文字檔案的第一行前兩個字元 #!

  • 以 #!/bin/sh 開頭的檔案,程式在執行的時候會呼叫 /bin/sh,也就是 bash 直譯器

  • 以 #!/usr/bin/python 開頭的檔案,代表指定 Python 直譯器去執行

  • 以 #!/usr/bin/env 直譯器名稱,是一種在不同平臺上都能正確找到直譯器的辦法。

注意事項

  • 如果指令碼未指定 shebang ,指令碼執行的時候,預設用當前 shell 去解釋指令碼,即 $SHELL

  • 如果 shebang 指定了可執行直譯器,比如 /bin/bash /user/bin/python ,指令碼在執行時,檔名會作為引數傳遞給直譯器

  • 如果 #!指定的解釋查詢沒有執行許可權,則會報錯

  • 如果 #!指定的解釋程式不是一個可執行檔案,那麼指定的解釋程式會被被忽略,轉交個當前的 SHELL 去執行這個指令碼

  • 如果你使用 bash text.sh 這樣的命令去執行指令碼,那麼 #!這一行就會被忽略掉,直譯器當然是用命令列中顯示指定的 bash

指令碼註釋

可以讓別人快速的讀懂你寫的指令碼,還有利於自己後期去更改基本。使用英文註釋,也可以用中文但是有可能會報錯。

shell執行方法

  • bash script.sh 或 sh scripte.sh,檔案本身沒有執行許可權,則使用的方法,或者指令碼未指定 sheban

  • 使用 絕對/相對 路徑來來執行指令碼

  • source script.sh 或者 ./script.sh,代表執行含義,source 等於 .

  • sh < script.sh 很少人用的一種方法

shell和運維

shell主要是來處理系統文字型別資料的,比如日誌配置檔案。shell 屬於弱型別的指令碼語言,無需聲名變數型別,直接定義使用。

history 歷史記錄

history            //檢視歷史記錄
history -c         //清除歷史記錄
history -r         //恢復歷史記錄

!+ 歷史記錄ID 快速使用歷史命令

!! 使用是一次命令

echo命令

-n    不換行輸出
-e    解釋字串中的特殊符號

\n    換行
\r    回車
\b    退格
\t    製表符(四個空格)

#eval    執行多個命令
eval ls;cd /temp

變數

pstree 檢查程序樹

變數定義與賦值,注意變數與值之間不得有空格

[root@shell ~]# name="花花"
[root@shell ~]# echo $name
花花

bash變數為弱型別,無需事先宣告型別,是將宣告和複製同時進行的

變數替換/引用

[root@shell ~]# music="花花"
[root@shell ~]# echo ${music}
花花
[root@shell ~]# echo $music
花花
[root@shell ~]# echo name
name

 

變數名規則

  1. 名稱定義要做到簡明知意,切按照規則來,切別的應用保留關鍵字

  2. 只能包含數字、字母、下劃線

  3. 不能以數字開頭

  4. 不能用標點符號

  5. 變數名嚴格區分大小寫

#有效字元
[root@shell ~]# age=15
[root@shell ~]# name = "花花" 
[root@shell ~]# _da=daf
[root@shell ~]# echo $_da
daf

#無效字元
[root@shell ~]# 2age=15
-bash: 2age=15: 未找到命令
[root@shell ~]# .age=55
-bash: .age=55: 未找到命令

變數作用域

父子關係:也就是說在父親裡的變數只能搜尋到父親的變數,搜尋不到兒子的。相反兒子的也是。

[root@shell ttt]# cat make_var.sh
age='18'
[root@shell ttt]# age='20'
[root@shell ttt]# echo $age
20
[root@shell ttt]# bash make_var.sh 
[root@shell ttt]# echo $age        
20
[root@shell ttt]# source make_var.sh 
[root@shell ttt]# echo $age         
18

環境變數

環境變數也成為全域性變數,針對當前 shell 以及其程序任意子程序,環境變數也分自定義變數、內建變數兩種

區域性變數

針對在 shell 中的函式或是 shell 指令碼中定義

位置引數變數

用於 shell 指令碼中傳遞的引數

特殊變數

shell 內建的特殊功效變數

  • $?

    1. 0: 成功

    2. 1-255:報錯

自定義變數

  • 變數賦值:varName=value

  • 變數引用:${varName}、$varName

單引號雙引號

單引號變數,不識別特殊語法 雙引號變數,能識別特殊符號

[root@shell ~]# name="小明" 
[root@shell ~]# echo ${name}
小明
[root@shell ~]# name2='${name}'
[root@shell ~]# 

變數特殊

shell 的變數,用在如指令碼,函式傳遞引數使用

$0        獲取 shell 指令碼檔名,以及指令碼路徑
$n        獲取 shell 指令碼的第 n 個引數,n 在1~9之間
$#        獲取執行的 shell 指令碼後面的引數總個數
$*        獲取 shell 指令碼所有引數,不加引號等同於$@作用。加上引號"$*"作用是,接受所有引數為單位字串。"$1 $2..."
$@        不加引號,效果同上,加引號接收到所有引數為獨立字串,如"$1" "$2" "$3"。如果用於for迴圈的話 $@ 收到的引數就會一個一個豎向的列出來

例項:

 1 [root@shell ttt]# cat make_var.sh 
 2 echo '特殊變數 $0'
 3 echo '結果' $0
 4 echo '-------------------'
 5 echo '特殊變數 $n'
 6 echo '結果' $1 $2 $3
 7 echo '-------------------'
 8 echo '特殊變數 $#'
 9 echo '結果' $#
10 echo '-------------------'
11 echo '特殊變數 $*'
12 echo '結果' $* 
13 echo '-------------------'
14 echo '特殊變數 $@'
15 echo '結果' $@ 
16 echo '-------------------'
17 [root@shell ttt]# bash make_var.sh gm 111 222 333 444 mmm        //make_var.sh 後面跟著的都是引數
18 特殊變數 $0
19 結果 make_var.sh
20 -------------------
21 特殊變數 $n
22 結果 gm 111 222
23 -------------------
24 特殊變數 $#
25 結果 6
26 -------------------
27 特殊變數 $*
28 結果 gm 111 222 333 444 mmm
29 -------------------
30 特殊變數 $@
31 結果 gm 111 222 333 444 mmm
32 -------------------
View Code

特殊狀態變數

$?        上一次命令執行狀態返回值,0為正確,非0為失敗
$$        當前 shell 指令碼的程序號
$!        上一次後臺程序號
$_        再次之前執行的命令,最後一個引數

修改變數設定

環境變數,能找出你的 linux 伺服器上的各種變數

  • 每個使用者都有自己的環境變數配置檔案,~/.bash_profile ~/.bashrc,且以個人配置檔案,優先加在變數,讀取,以個人的優先生效

  • 當你需要給所有使用者都使用某個變數,寫入全域性即可 /etc/profile

檢查系統環境變數命令

  • set:輸出所有變數,包括全域性變數、區域性變數

  • env:只顯示全域性變數

  • declare:輸出所有的變數,如同set

  • export:顯示和設定環境變數值

[root@shell ~]# set
BASH=/usr/bin/bash
....
[root@shell ~]# set |wc -l                //顯示的行數
55
[root@shell ~]# env 
XDG_SESSION_ID=13
....
[root@shell ~]# env | wc -l
21

設定只讀變數

readonly,只有 shell 結束,只讀變數實效

[root@shell ~]# readonly password="123"
[root@shell ~]# echo $password
123
[root@shell ~]# password="123456"
bash: password: 只讀變數

系統保留環境變數關鍵字

bash 內嵌了諸多環境變數,用於定義 bash 的工作環境

# 去除空格冒號等於號 第三列的值
[root@shell ~]# export |awk -F '[ :=]' '{print $3}'
HISTCONTROL
......

bash 命令執行

開啟一個子程序單獨來執行指令碼

[root@shell etc]# ls /opt/ ; ls /proc/ ; cd /etc/
[root@shell etc]# bash SEHELL.sh

字串擷取

#    從開頭刪除匹配最短
##    從開頭刪除匹配最長
%    從結尾刪除匹配最短
%%    從結尾刪除匹配最長

//指定字元內容擷取
a*c    匹配開頭為a,中間任意個字元,結尾為c的字串

//語法
name="huahua"    #該變數的值,有所索引,分別是從 0,1,2,3,4開始

$(變數)    返回變數值
$(#name)    返回變數長度,字元長度
$(變數:start)    返回變數start數值之後的字元,且包含start的數字
$(變數:start:start)    提取start之後的length限制的字元,例如:${name:4:1}
$(變數#word)    從變數開頭刪最短word字串,例如:${name:hua}
$(變數##word)    從變數開頭刪最長word字串
$(變數%word)    從變數結尾刪除最短word
$(變數%%word)    從變數結尾刪除最長匹配word

替換
${變數/patter/string}    用string代替第一個匹配的pattern
${變數//patter/string}    用string替代所有pattern

shell 運算子

運算命令

特殊符號運算

++    加一
--    減一

++a    先計算+1,然後再賦值給a
a++    先對變數a操作,在進行+1

例項
[root@shell ttt]# a=4
[root@shell ttt]# echo $((++a))
5
[root@shell ttt]# echo $((a++))
5
[root@shell ttt]# echo $a
6

函式

函式作用,就是把你寫的功能程式碼,進行打包,封裝成一個函式名,然後進行呼叫數名,函式就會執行

注意

函式定義完一定要呼叫、執行要不使用不了。

指令碼開發

指令碼開發思路:

  1. 想好該指令碼的功能

  2. 先寫虛擬碼

例項1:使用者輸入值來計算

開發一個,接受使用者輸入的數字,且對運算子號判斷,最終得出一個計算指令碼

  1. 接受使用者輸入

  2. 對使用者的輸入是不是數字進行判斷

  3. 對輸入的運算子號進行判斷

  4. 最終進行結列印

[root@shell ttt]# touch calculation.sh
[root@shell ttt]# chmod +x calculation.sh
[root@shell ttt]# cat calculation.sh 
#!/bin/bash
print_usage(){
        print "please enter aninteger\n"
        exit 1
}

read -p "Please input your number: " firstnum
if [ -n "`echo $firstnum | sed 's/[0-9]//g'`" ]
        then
                print_usgae
fi

read -p "Please input your: " operator
if [ "${operator}" != "+" ] && [ "${operator}" != "-" ] && [ "${operator}" != "*" ] && [ "${operator}" != "/" ]
        then
                echo "只允許輸入 +|-|*|/"
                exit 2
fi

read -p "please input number: " secondnum
if [ -n "`echo $secondnum | sed 's/[0-9]//g'`" ]
        then
                print_usage
fi

echo "${firstnum}${operator}${secondnum}結果:$((${firstnum}${operator}${secondnum}))"
 1 #!/bin/bash
 2 
 3 #定義函式 函式名為 print_usage 。 exit 1 就是當你輸入 echo $? 到時候返回的值
 4 print_usage(){
 5         print "please enter aninteger\n"
 6         exit 1
 7 }
 8 
 9 #接受使用者輸入命令,-p引數後面寫,給使用者看的提示資訊。read -p "提示資訊" 接受使用者輸入的變數
10 read -p "Please input your number: " firstnum
11 
12 #if 判斷中括裡前後加空格隔開中括號,格式要求。-n 引數是 if 語句,對字串判斷,如果字串問空,條件就不成立,如果字串不為空,條件成立。sed 的作用就是講使用者輸入的值進行解析,看是不是 0-9 的數字,是就下一步不是就成立就不執行程式碼。fi 是閉合 if 語句
13 if [ -n "`echo $firstnum | sed 's/[0-9]//g'`" ]
14         then
15                 print_usgae
16 fi
17 
18 read -p "Please input your: " operator
19 if [ "${operator}" != "+" ] && [ "${operator}" != "-" ] && [ "${operator}" != "*" ] && [ "${operator}" != "/" ]
20         then
21                 echo "只允許輸入 +|-|*|/"
22                 exit 2
23 fi
24 
25 read -p "please input number: " secondnum
26 if [ -n "`echo $secondnum | sed 's/[0-9]//g'`" ]
27         then
28                 print_usage
29 fi
30 
31 #echo 輸出三個使用者輸出的引數在進行運算
32 echo "${firstnum}${operator}${secondnum}結果:$((${firstnum}${operator}${secondnum}))"
指令碼解釋

例項2:Nginx 服務是正常執行

隨便一個虛擬機器開啟安裝一個 nginx 開啟服務來測試

[root@shell ttt]# touch chare_nginx.sh
[root@shell ttt]# chmod +x chare_nginx.sh
[root@shell ttt]# cat chare_nginx.sh 
#!/bin/bash
CheckUrl(){
  timeout=5
  fails=0
  success=0
  
  while true
    do
       wget --timeout=${timeout} --tries=1 http://192.168.100.20/ -q -O /dev/null
      
      if [ $? -ne 0 ]
          then
              let fails=fails+1
          else
              let success+=1
        fi

        if [ ${success} -ge 1 ]
           then
               echo "health"
               exit 0
        fi
      
        if [ ${fails} -ge 2 ]
           then
                echo "nixng 出錯"
                exit 2
       fi
  done
}

CheckUrl

[root@shell ttt]# ./chare_nginx.sh         #執行成功
health
[root@shell ttt]# ./chare_nginx.sh      #執行失敗輸出
nixng 出錯
 1 [root@shell ttt]# cat chare_nginx.sh 
 2 #!/bin/bash
 3 CheckUrl(){
 4 
 5   timeout=5      #超時時間 5 秒
 6   fails=0      #失敗次數。相當於定義了一個計數器
 7   success=0        #成功次數。相當於定義了一個計數器
 8 
 9   while true    #while 迴圈 true 為真
10     do
11        #wget 來訪問站點、函式timeout傳給--timeout、--tries是wget的重連極致、URL、-q是不顯示資訊、-O是寫入 /dev/null
12        wget --timeout=${timeout} --tries=1 http://192.168.100.20/ -q -O /dev/null
13   
14       #if 條件判斷 -ne:不等於 
15        if [ $? -ne 0 ]        #當 echo $? 不等於0時
16           then
17               let fails=fails+1        #不等於0失敗次數+1
18           else        #當 echo $? 等於0時
19               let success+=1        #等於0成功次數+1
20 
21         fi
22         
23         #if 判斷語句 -ge:大於
24         if [ ${success} -ge 1 ]        #當成功次數大於一時
25            then
26                 echo "health"        #就輸出 health
27                 exit 0                #echo $? 值
28         fi
29          
30         #當錯誤底數大於2是告警,可以發郵箱、簡訊等。
31         if [ ${fails} -ge 2 ]        
32             then
33                 echo "nixng 出錯"        #報錯就輸出
34                 exit 2
35         fi
36   done        #結束
37 }
38 
39 #注意,函式定義後,一定要呼叫,執行
40 CheckUrl    
指令碼解釋

alias 函式命令

定義 linux 別名函式

[root@shell ttt]# alias hua="cat make_var.sh"
[root@shell ttt]# hua
#!/bin/bash

if expr "$1" ":" ".*\.jpg" &> /dev/null
   then
       echo "正確"
else
    echo "失敗"
fi

# 這是 linux 的所以別名
[root@shell ttt]# alias
alias cp='cp -i'
alias egrep='egrep --color=auto'
alias fgrep='fgrep --color=auto'
alias grep='grep --color=auto'
alias hua='cat make_var.sh'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

shell 函式開發指令碼

函式特點,類似於 alias 別名一樣,能夠簡化 linux 命令的操作,讓整個命令更容易讀,更容易用

  • 函式,就是你需要執行的 shell 命令,組合起來,組成一個函式體

  • 還得給這個函式體,起一個名字,這個名字就是函式名

  • 函式名+函式體

  • 以後你想執行這個函式,就使用這個函式名即可

1. 先定義函式
2. 呼叫函式

# 這就是一個一個函式體了,每次呼叫都會輸出 “阿花程式碼”
sayHello(){
    echo "阿花程式碼“
}

函式定義語法

# 標準函式定義
function 函式名(){
    函式體
    你想執行的 linux 命令 ....
    return 返回值
}

# shell 老司機
函式名(){
    函式體
    程式碼...
    return 返回值
}

 

執行函式

  • 執行函式概念

  • 執行 shell 函式,直接寫函式名即可,無需新增其他內容

  • 函式必須先定義,在執行,shell 指令碼自上而下載入

  • 函式體內需要新增 return 語句,作用是退出函式,且賦予返回值給呼叫該函式的程式,也就是 shell 指令碼

  • return 語句和 exit 不同

    1. return 是結束函式的執行,返回值(提出值、返回值)

    2. exit 是結束 shell 環境,返回一個(提出值、返回值)給當前的 shell

  • 函式如果單獨寫入一個檔案裡,需要用 source 讀取

  • 函式內,使用 local 關鍵字,定義區域性變數

函式實戰

查詢使用者輸入的網站是否正常執行

[root@shell ttt]# vim url_test.sh
usage(){
   echo "Usage: $0 URL"
   exit 1
}

check_url(){

   # wget 來連結使用者輸入的網址、--spider 身份資訊、-q -o是寂寞輸出不想看到任何結果、--trues 連結一次、-T 睡眠5秒、$1 是使用者輸入的 URL
   wget --spider -q -o /dev/null --tries=1 -T 5 $1
   
   # if 判斷、$? 如果狀態碼等於零輸出....、不等於0輸出.....
   if [ "$?" -eq 0 ]
      then
         echo "$1 is runing..."
   else
         echo "$1 is down..."
   fi
}

#人口函式。也需要呼叫
main(){
    # if 判斷使用者輸入的是不是一個值,不是就返回 usage 函式
    if [ "$#" -ne 1 ]
       then
           usage
    else
          check_url $1
    fi
}
#呼叫 main 函式、$* 當用戶進來的引數當個整體
main $*
[root@shell ttt]# ./url_test.sh baidu.com
baidu.com is runing...

美化輸出

這是 linux 自帶的

在輸出前面加上 log_success_msg() 和 log_failure_msg() 就可以了

expr命令

expr命令是一個手工命令列計數器,用於在UNIX/LINUX下求表示式變數的值,一般用於整數值,也可用於字串。

[root@shell ~]# expr --help        #檢視引數
[root@shell ~]# expr 4 \+ 5        #4+5=9
9

exper匹配模式

exper 命令支援沒事匹配功能,且有兩個特殊符號:

: 冒號,計算字串的字元數量

.* 任意的字串重複0次或者多次

例項:

[root@shell ~]# expr ahkl  ":" ".*"
4
[root@shell ~]# expr asn.png ":" ".*\.png" 
7

指令碼開發

題目:測試使用者提交的是否是 .jpg 檔案

[root@shell ttt]# cat make_var.sh 
#!/bin/bash

if expr "$1" ":" ".*\.jpg" &> /dev/null        #如果 $1 字尾是 .jpg 傳入 /dev/null 黑洞檔案
   then
       echo "正確"
else
    echo "失敗"
fi
[root@shell ttt]# ./make_var.sh 1.jpg
正確

數值計算

bc命令

是一個計算機命令、支援 awk 數值計算、中括號運算

1.可以直接輸入 bc 進入計算機狀態進行計算
2.結合管道符來進行計算
[root@shell ~]# echo "5 * 6"
5 * 6
[root@shell ~]# echo "5 * 6" | bc
30

例項:

題目1+100的總和

1 xxxxxxxxxx 方法1:[root@shell ~]# echo {1..100}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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100# tr 是替換命令[root@shell ~]# echo {1..100} | tr " " "+" | bc5050方法2:#seq命令 -s是分隔符[root@shell ~]# seq -s "+" 1001+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+31+32+33+34+35+36+37+38+39+40+41+42+43+44+45+46+47+48+49+50+51+52+53+54+55+56+57+58+59+60+61+62+63+64+65+66+67+68+69+70+71+72+73+74+75+76+77+78+79+80+81+82+83+84+85+86+87+88+89+90+91+92+93+94+95+96+97+98+99+100[root@shell ~]# seq -s "+" 100 | bc5050
例項 1...100 和

awk運算

AWK 是一種處理文字檔案的語言,是一個強大的文字分析工具。

[root@shell ttt]# echo "5 6"
5 6
[root@shell ttt]# echo "5 6" | awk '{print $1+$2}'
11

中括號計算

[root@shell ttt]# num=5
[root@shell ttt]# res=$[num*6]
[root@shell ttt]# echo $res
30

read 命令

準輸入讀取數值

# -t 是時間引數,超過後面的時間就禁止輸入了、-p 設定提示資訊
[root@shell ttt]# read -t 15 -p "請輸入你的名字:"
請輸入你的名字:[root@shell ttt]# 

#後面跟 name 變數就是使用者所輸入的
[root@shell ttt]# read -t 15 -p "請輸入你的名字:" name
請輸入你的名字:花花
[root@shell ttt]# echo $name
花花

shell條件測試

語法:

語法:(針對檔案型別判斷的真假)
-e 該『檔名』是否存在?(常用)
-f 該『檔名』是否為件(file)?(常用)
-d 該『檔名』是否為目錄(directory)?(常用)
-b 該『檔名』是否為一個 block device裝置?
-c 該『檔名』是否為一個character device裝置?
-S 該『檔名』是否為一個 Socket檔案?
-p 該『檔名』是否為一個FIFO (pipe)檔案?
-L 該『檔名』是否為一個連結檔?

2.關於檔案的許可權偵測,如 test -r filename
-r 偵測該檔名是否具有『可讀』的屬性?
-w 偵測該檔名是否具有『可寫』的屬性?
-x 偵測該檔名是否具有『可執行』的屬性?
-u 偵測該檔名是否具有『SUID的屬性?
-g 偵測該檔名是否具有『SGID』的屬性?
-k 偵測該檔名是否具有『sticky bit的屬性?
-s 偵測該檔名是否為『非空白檔案』?

3.多重條件判定,例如:test-r檔名-a-x檔名
-a (and)兩狀況同時成立!例如test -r file -a -x file,則 file同時具有r與x許可權時,才回傳 true。
-o(or)兩狀況任何一個成立!例如test file -o -x file,則 file具有r或×許可權時,就可回傳true。
! 反相狀態,如test ! -x file ,當file 不具有×時,回傳 true

-z 是沒有字串返回真有則返回假。-n 正好相反
.....

test條件測試

test 命令評估一個表示式,它的結果是真,還是假,如果條件為真,那麼命令執行狀態碼結果就為 0 否則就是不為 0,通過 $? 取值

test 命令引數:-a (and)兩狀況同時成立!例如test -r file -a -x file,則 file同時具有r與x許可權時,才回傳 true。 -A(和)兩狀況同時成立!例如測試-r檔案-a-x檔案,則檔案同時具有r與x許可權時,才回傳true.

例項:

#檢視是否有 1.jpg 這個檔案有就返回值“有檔案”,沒建立一個
[root@shell ttt]# test -e 1.jpg && echo "有檔案" || touch 1.jpg
有檔案

#-z 是沒有字串返回真有則返回假。-n 正好相反
[root@shell ttt]# test -z "" && echo ok || echo no 
ok
[root@shell ttt]# test -z " " && echo ok || echo no 
no

中括號條件測試

指令碼中經常進行條件測試,用的最多的一個。中括號跟 test 作用是一樣的

注意:

  1. 中括號,前後的空格必須有

  2. 條件測試裡有變數的時候要帶雙引號

例項:

#-f 判斷檔案是否存在
[root@shell ttt]# [ -f test.sh ] && echo "已存在" || touch test.sh
[root@shell ttt]# [ -f test.sh ] && echo "已存在" || touch test.sh
已存在

雙中括號條件測試

跟中括號和 test 一樣

例項:

[root@shell ttt]# [[ -f test.sh ]] && echo "已存在" || touch test.sh
已存在

字串比較測試

 例項:

[root@shell ttt]# name=123
[root@shell ttt]# age=123
[root@shell ttt]# [ "$name" = "$age" ] && echo "一樣" || echo "不對"
一樣

數值比較

條件引數:

[root@shell ttt]# [ 2 \< 1 ] && echo yes || echo no
no
[root@shell ttt]# [ 2 -lt 1 ] && echo yes || echo no  
no

[root@shell ttt]# [[ 2 -lt 1 ]] && echo yes || echo no
no
[root@shell ttt]# [[ 2 < 1 ]] && echo yes || echo no   
no

[root@shell ttt]# nt=5
[root@shell ttt]# bt=3
[root@shell ttt]# test "$nt" -lt "$bt" && echo yes || echo no
no

邏輯判斷符號

[root@shell ttt]# a=1.jpg 
[root@shell ttt]# b=test.sh 
[root@shell ttt]# [ -e "$a" -a "$b" ] && echo yes || echo no  
yes
#在中括號中 && || 識別不了。雙中括號可以
[root@shell ttt]# [ -e "$a" && "$b" ] && echo yes || echo no
-bash: [: 缺少 `]'
no

指令碼開發

[root@shell ttt]# vim test.sh
#!/bin/bash
path=root/ttt/

[ ! -d "$path" ] && mkdir $path -p

cat <<END
   1.[install lamp]
   2.[install lnmp]
   3.[exit]
END

read num

[[ ! "$num" =~ [1-3] ]] && {
    echo "The num you iput must be {1|2|3}"
    echo "輸入有誤"
    exit 4
}  

[ "$num" -eq 1 ] && {
     echo "Start installing ... lamp..."
     sleep 2;
     [ -x "$path/lamp.sh" ] || {
             echo "The file is error..."
             exit 1
     }
     source $path/lamp.sh
     echo $?
}

[ "$num" -eq 2 ] && {
    echo "Start installing ... lnmp..."
    sleep 2;
     [ -x "$path/lnmp.sh" ] || {
             echo "The file is error..."
             exit 2
     }
     source $path/lamp.sh
     echo $?
}

[ "$num" -eq 3 ] && {
    echo "ByeBye"
    exit 3;
}

[root@shell ttt]# ./test.sh   
   1.[install lamp]
   2.[install lnmp]
   3.[exit]
3
ByeBye
[root@shell ttt]# ./test.sh 
   1.[install lamp]
   2.[install lnmp]
   3.[exit]
qe
The num you iput must be {1|2|3}
輸入有誤
 1 #!/bin/bash
 2 path=root/ttt/        //檢視是否有這個目錄
 3 
 4 [ ! -d "$path" ] && mkdir $path -p        //沒有這個目錄就建立一個
 5 
 6 cat <<END                //給使用者看的提示
 7    1.[install lamp]
 8    2.[install lnmp]
 9    3.[exit]
10 END
11 
12 read num    //使用者輸入的變數
13 
14 # 然後沒有按照固定輸入就提示報錯。
15 [[ ! "$num" =~ [1-3] ]] && {
16     echo "The num you iput must be {1|2|3}"
17     echo "輸入有誤"
18     exit 4        //結束shell
19 }  
20 
21 #當用戶輸入 1 時,提示使用者正在安裝,沉睡兩秒。
22 [ "$num" -eq 1 ] && {
23      echo "Start installing ... lamp..."
24      sleep 2;
25      #檢視這個 lamp.sh 安裝lamp是否有許可權
26      [ -x "$path/lamp.sh" ] || {
27              echo "The file is error..."
28              exit 1
29      }
30      # 執行指令碼
31      source $path/lamp.sh
32      echo $?    
33 }
34 
35 [ "$num" -eq 2 ] && {
36     echo "Start installing ... lnmp..."
37     sleep 2;
38      [ -x "$path/lnmp.sh" ] || {
39              echo "The file is error..."
40              exit 2
41      }
42      source $path/lamp.sh
43      echo $?
44 }
45 
46 [ "$num" -eq 3 ] && {
47     echo "ByeBye"
48     exit 3;
49 }
指令碼解釋

if 語句

語法:

單分支

if <條件分支>
   then
       執行程式碼...
fi

雙分支

if <條件分支>
   then
       執行程式碼...
         if <條件分支>
              then
                 執行程式碼...
         fi
fi

if - else

if <條件分支>
   then
       執行程式碼...
else
     否則幹嘛...
fi

多分支

elif 可以寫多個

if <條件分支>
   then
       執行程式碼...
elif
    then
        又如果幹嘛...
else
       否則幹嘛...
fi

記憶體檢測指令碼

開發 shell 指令碼

1.檢測 linux 剩餘的可用記憶體,當可用記憶體小於 100m,就發郵件給運維

2.並且該指令碼加入 crontab,每三分鐘檢測一次

思路
1. 獲取當前記憶體
2. 配置郵件告警,用 linux 傳送郵件(mail服務的配置),郵件內容是記憶體剩餘情況
3. 開發指令碼,判斷剩餘記憶體是否小於 100m,if判斷
4. 指令碼加入 crontab,寫規則
#檢視記憶體使用情況
[root@shell ttt]# free -m
              total        used        free      shared  buff/cache   available
Mem:           1819         195        1202           9         421        1462
Swap:          2047           0        2047
#提取可用記憶體值
[root@shell ttt]# free -m |awk 'NR==2 {print $NF}'
1462

[root@shell ttt]# cat test.sh 
#!/bin/bash

FreeM=`free -m |awk 'NR==2 {print $NF}'`
CHARS="Current memory is $FreeM"

if [ "$FreeM" -lt "2000" ]        // -lt 小於
   then
      echo $CHARS|tee /ttt/FREEMEM
      # mail 服務需要自己配置 、-s 主題、收件人、< 內容
#     mail -s "`data +%F-%T`$CHARS" [email protected] < /tmp/FREEMEM
      echo "記憶體不足"
fi

[root@shell ttt]# ./test.sh 
Current memory is 1462
記憶體不足
[root@shell ttt]# cat FREEMEM 
Current memory is 1462

Mysql 監控指令碼

伺服器本地埠監控,mysql 的狀態

#下面的程式碼只要不返回 0 就代表 mysql 正常執行
[root@shell ~]# netstat -tunlp | grep mysql | wc -l
1
[root@shell ~]# ss -tunlp | grep mysql |wc -l
1
[root@shell ~]# lsof -i tcp:3306 |wc -l
2

遠端監控 mysql 埠

yum install -y nmap nc    //需要下載

# nmap 掃描埠
[root@shell ~]# nmap 127.0.0.1 -p 3380 |grep open|wc -l        //IP可以更改為服務端
1


# telnet 遠端登入埠
[root@shell ~]# echo -e "\n" |telnet 127.0.0.1 3380 2>/dev/null |grep Connected |wc -l
1

程序檢查

# grep -v grep 過濾掉 grep 的
[root@shell ~]# ps -ef | grep mysql |grep -v grep |wc -l
0

shell 指令碼檢測 mysql 狀態

[root@shell ttt]# vim mysql_shell.sh
#!/bin/bash
if [ `netstat -tunlp |grep mysql |wc -l` = "1" ]        //將裡面的引數修改即可、使用 lsof 到時候要注意
   then
       echo "Mysql suvival"
else
       echo "Mysql drop"
fi
[root@shell ttt]# ./Mysql_shell.sh 
Mysql drop

PHP連結Mysql

1.準備好依賴
yum remove php-mysql
yum install php-mysqlnd php

2.寫指令碼
[root@shell ttt]# vim mysql_test.php
<?php
# 定義連結、呼叫 mysql_connect 函式、出錯的話就連結 mysq_error 這個函式
$mysql_id=mysql_connect("localhost","root","password") of mysql_error();

if ($mysql_id){
   echo "mysql connection successful,huahua ~~~";
}else{
   echo mysql_error();
}
?>
[root@shell ttt]# php msyql_test.php
mysql connection successful,huahua ~~~

Python 連結 mysql

1. 安裝 Python 開發環境的依賴
yum install python3 python3-devel python3-pip
2. 通過 python 的包管理工具,安裝 mysql 模組
pip3 install pymysql
3. 寫指令碼
[root@shell ttt]# vim python_mysql.py
#匯入模組
import pymysql

#變數 db 傳參
db = pymysql.connect(
   host="localhost"
   port="3306"
   user='root'
   password="password"
   db="msyql"
   charset="utf8"
)

#操控資料庫
cursor=db.cursor()   
cursor.execute('select version()')        //執行語句
data=cursor.fetchone()        //拿到資料
print("資料庫版本是:%s"%data)
db.close()                //關閉資料庫連結