shell編程

Shell入門

什么是shell店量?

Shell其實是一個命令解釋器翘紊,作用是解釋執(zhí)行用戶輸入的命令以及程序等余佃,用戶每輸入一條命令暮刃,Shell給予解釋執(zhí)行一條。這種鍵盤一輸入命令爆土,就可以立即得到回應(yīng)的對話方式椭懊,稱為交互模式。
Shell存在于操作系統(tǒng)的最外層步势,負責與用戶直接對話氧猬。處理用戶的輸入背犯,并將操作系統(tǒng)執(zhí)行結(jié)果返回給用戶。在用戶登陸到操作系統(tǒng)之后的所有操作均由Shell解釋執(zhí)行盅抚。Shell在操作系統(tǒng)中所處的位置如下

image

什么是shell腳本漠魏?

簡言之,如果shell命令通過寫入到一個程序文件并執(zhí)行的時候妄均,此程序我們就稱之為shell腳本柱锹。但是在生產(chǎn)環(huán)境中的Shell腳本不僅僅是這么簡單,而是將一些命令丛晦、變量以及流程控制語句有機結(jié)合并生成的功能完善的強大的應(yīng)用程序奕纫。

什么時候使用shell腳本?

Linux批量管理
自動化完成系統(tǒng)優(yōu)化
自動化安裝Linux操作系統(tǒng)(kickstart和cobbler)
測試工具和內(nèi)容自動化
郵件自動發(fā)送
服務(wù)自動重啟
代碼上線
定時備份和定時啟停服務(wù)
Linux系統(tǒng)監(jiān)控烫沙、服務(wù)監(jiān)控匹层、端口監(jiān)控、IP黑名單監(jiān)控锌蓄、流量監(jiān)控(腳本+zabbix)
服務(wù)的日志切割升筏、存儲備份、日志分析等等

如何學(xué)好shell腳本瘸爽?

基礎(chǔ)變量您访、條件表達式、流程判斷剪决、if灵汪、for循環(huán)、while循環(huán)柑潦、case語句享言、循環(huán)控制
從簡單的判斷和循環(huán)開始寫
閱讀、模仿、嘗試從零開始寫
寫注釋,將任務(wù)分解成一個個小任務(wù)口糕,類似于打游戲闖關(guān)
找一本合適的教材,或者自己認真記筆記
多練習(xí)-思考-練習(xí)-思考差牛,循環(huán)往復(fù)

解釋型語言和編譯型語言

編譯型語言:

指用專用的編譯器,針對特定的操作平臺(操作系統(tǒng))將某種高級語言源代碼一次性翻譯成可被硬件平臺直接運行的二進制機器碼堰乔,這個過程叫做編譯偏化。
編譯好的可執(zhí)行文件(.exe),可在相對應(yīng)的平臺運行(移植性差镐侯,但是效率高)夹孔。
C\C++.....

解釋型語言:

用專門解釋器對源程序逐行解釋成特定平臺的機器碼并立即執(zhí)行的語言,相當于把編譯型語言的編譯執(zhí)行過程混合在一起同時完成的析孽。
編譯型語言執(zhí)行效率較低搭伤,切不能脫離解釋器運行。但是跨平臺比較容易袜瞬,只需提供相應(yīng)的解釋器
shell\python
注:Java屬于特殊的怜俐。既可以說成是解釋型語言,又可以說成是編譯型語言

shell是命令解釋器
shell腳本是由命令組合成的一個可執(zhí)行的文件
編譯型語言和解釋型語言

shell腳本建立和執(zhí)行

解釋器類型

bash是centos中的默認解釋器
sh

腳本定義

腳本開頭

# !/bin/bash

父shell和子shell

腳本嵌套
父shell中的環(huán)境變量邓尤,在子shell中可以看到
而子shell中的變量拍鲤,在父shell中看不到

shell執(zhí)行方式

sh & bash,最常用的使用方式
cat *.sh | bash汞扎,適用于執(zhí)行多個腳本
sh < oldboy.sh季稳,了解一下,輸入重定向
/root/oldboy.sh澈魄,需要執(zhí)行權(quán)限
. oldboy.sh
source oldboy.sh

shell開發(fā)習(xí)慣

? 腳本存放在固定目錄
? 開頭加腳本解釋器信息
? 附帶作者和版權(quán)信息
? 腳本中盡量不用中文
? 腳本擴展名用.sh
? 成對的符號一次性書寫完成
? 注意縮進
? 養(yǎng)成寫注釋的良好習(xí)慣

總結(jié)

腳本放在指定目錄
創(chuàng)建腳本景鼠,后綴是.sh
在第一行頂格添加命令解釋器的聲明#!/bin/bash
添加作者時間和版權(quán)信息
養(yǎng)成良好習(xí)慣,添加注釋
Centos7默認解釋器是/bin/bash
退出當前shell的命令是:exit
有一個小問題:在使用history的時候痹扇,加入腳本中铛漓,執(zhí)行什么也不會輸出。
在腳本中加入set -o history即可解決鲫构,但是默認顯示的是這個腳本里的歷史命令浓恶。但是
如果還想顯示腳本外的歷史記錄,可以使用source 執(zhí)行腳本结笨。

變量基礎(chǔ)

定義變量

值可變的量包晰,稱為變量
變量名=變量值,常說的變量炕吸,一般是變量名
字母數(shù)字下劃線伐憾,不能是數(shù)字開頭

環(huán)境變量和普通變量

環(huán)境變量(全局變量)

? 可在創(chuàng)建他們的shell以及派生出來的任意子shell中使用
? 環(huán)境變量包括內(nèi)置的環(huán)境變量和自定義的環(huán)境變量,且通常為大寫算途。
? 環(huán)境變量的定義方式:

declare -x 變量名=value
export 變量名=value

? 環(huán)境變量有四個文件塞耕,他們的執(zhí)行順序如下圖所示:

image

? 登陸shell會加載所有的環(huán)境變量
? 非登陸shell可能會加載~/.bashrc或者/etc/bashrc(上圖非綠色部分),然而有些定時任務(wù)以上兩個根本不會加載嘴瓤,所以需要手動指定扫外,建議在定義變量時定義到/etc/bashrc
? 可以在環(huán)境變量文件中定義普通變量

普通變量

? 普通變量只有在當前shell下才能使用
? 定義方式
# 適用于一般場景,不適用于帶有空格等字符
變量名=value
# 所見即所得的定義方式
變量名=’value’
# 解析雙引號之內(nèi)的變量
變量名=”value

? 注意點:(舉例說明)

  1. 變量如果后面有內(nèi)容廓脆,一定要把變量括{}起來
  2. 希望變量內(nèi)容原樣輸出則加單引號
  3. 希望獲取變量中的命令執(zhí)行結(jié)果用``或者$()

1筛谚、定義環(huán)境變量的方式:
export 變量名=變量值
2、定義普通變量的方式:
變量名=變量值
3停忿、定義變量的三種方式

# 適用于一般場景驾讲,不適用于帶有空格等字符
[export] 變量名=value
# 所見即所得的定義方式
[export] 變量名=’value’
# 解析雙引號之內(nèi)的變量
[export] 變量名=”value”
4、環(huán)境變量文件的加載順序
/etc/profile ===> ~/.bash_profile ===> ~/.bashrc ===> /etc/bashrc
5、非登錄式(ssh)的shell只加載后兩個

臨時變量和永久變量(了解)

如果按照變量的生存周期來劃分的話吮铭,Linux變量可以分為兩類:
? 永久變量:需要修改變量配置文件时迫,使得變量永久生效
? 臨時變量,使用export命令或者直接在當前shell中賦值的變量

shell特殊變量

參數(shù)特殊變量

特殊變量 作用說明
0獲取當前執(zhí)行shell腳本文件名谓晌,如果執(zhí)行腳本帶路徑掠拳,則包括完整路徑
n獲取當前執(zhí)行腳本的第n個參數(shù)值,若n>9,則用大括號包裹纸肉,如10#傳遞到腳本的參數(shù)個數(shù)
*以一個單字符串顯示所有向腳本傳遞的參數(shù)@與$*相同溺欧,但是使用時加引號,并在每個引號中返回每個參數(shù)
n 獲取當前執(zhí)行shell腳本的第n個參數(shù)值柏肪,若n>9姐刁,則用大括號包裹,如10#
傳遞到腳本的參數(shù)個數(shù)
*以一個單字符串顯示所有向腳本傳遞的參數(shù)@ 與$*相同烦味,但是使用時加引號聂使,并在引號中返回每個參數(shù)。

進程特殊變量

特殊變量 作用說明
拐叉?顯示最后命令的特殊狀態(tài)岩遗,0表示沒有錯誤,非0表示有錯誤凤瘦。此變量最常用的$$顯示腳本
! 后臺運行的最后一個進程的ID號宿礁,此變量不常用,了解即可
$_ 之前運行腳本的最后一個參數(shù)蔬芥,此變量最不常用梆靖,了解即可

shell變量子串

表達式 作用說明
{param} 返回變量param內(nèi)容
{#param} 返回變量param內(nèi)容的字符長度,也適合特殊變量笔诵,此表達式最常用
{param:offset} 在變量param中返吻,從位置offset之后開始提取子串到結(jié)尾
{param:offset:length} 在變量param中,從位置offset之后開始提取長度為length的子串
{param#word} 在變量param開頭刪除最短匹配的word子串
{param##word} 在變量param開頭刪除最長匹配的word子串
{param%word} 在變量param結(jié)尾刪除最短匹配的word子串
{param%%word} 在變量param結(jié)尾刪除最長匹配的word子串
{param/pattern/string} 將變量param中符合pattern的第一個內(nèi)容用string取代
{param//pattern/string} 將變量param中符合pattern的所有內(nèi)容用string取代

總結(jié):獲取變量字符串長度的五種方法:

[root@shell ~]# oldboy="www.oldboy.com"
[root@shell ~]# echo ${#oldboy}
14
[root@shell ~]# echo ${oldboy} |wc -L
14
[root@shell ~]# expr length $oldboy
14
[root@shell ~]# echo ${oldboy}|awk '{print length}'
14
[root@shell ~]# echo ${oldboy}|awk '{print length($0)}'
14

練習(xí):

1乎婿、 請使用shell腳本打印下面語句中字符數(shù)不小于6的單詞
I am teacher oldchang and I like eating and sleeping

for n in $*                                  
do
    [ ${#n} -ge 6 ] && echo $n
done

2测僵、 寫出shell腳本,通過傳參的方式谢翎,傳入以下內(nèi)容捍靠,并打印下面語句中字符數(shù)不小于6的單詞
I am teacher oldchang and I like eating and sleeping

read -p '請輸入你要處理的字符串: ' n
for n in $n
do
    if [ ${#n} -ge 6 ];then                
        echo $n
    fi
done

變量傳參

腳本變量傳參的三種方式:
? 直接賦值

[oldchang@oldboy-node101 ~]$ cat 1.sh 
IP=127.0.0.1
echo $IP
[oldchang@oldboy-node101 ~]$ sh 1.sh 
127.0.0.1

? 傳參方式

[oldchang@oldboy-node101 ~]$ cat 1.sh 
IP=$1
echo $IP
[oldchang@oldboy-node101 ~]$ sh 1.sh 127.0.0.1
127.0.0.1

? read方式

[oldchang@oldboy-node101 ~]$ cat 1.sh 
read -p "請輸入一個參數(shù): " IP
echo $IP
[oldchang@oldboy-node101 ~]$ sh 1.sh 
請輸入一個參數(shù): 127.0.0.1
127.0.0.1

運算符與運算命令

image
image
image
[root@shell scripts]# a=8
[root@shell scripts]# echo $((a%6))
2
[root@shell scripts]# echo $a
8
[root@shell scripts]# echo $((a%=6))
2
[root@shell scripts]# echo $a
2

練習(xí)取值

[root@oldboyedu ~]# echo 1+1 | bc
2
[root@oldboyedu ~]# echo 3.3*8.7 | bc
28.7
[root@oldboyedu ~]# echo "scale=4;3.3*8.7" | bc
28.71
[root@oldboyedu ~]# echo "scale=4;3.33*8.7" | bc
28.971
[root@oldboyedu ~]# echo "scale=4;3.333*8.7" | bc
28.9971
[root@oldboyedu ~]# echo "scale=4;3.3333*8.7" | bc
28.9997
[root@oldboyedu ~]# echo "scale=10;3.3333*8.7" | bc
28.99971
[root@oldboyedu ~]# echo 1 2 | awk '{print $1}'
1
[root@oldboyedu ~]# echo 1 2 | awk '{print $1+$2}'
3
[root@oldboyedu ~]# echo 3.4 2 | awk '{print $1+$2}'
5.4
[root@oldboyedu ~]# echo 3.4 2.444444 | awk '{print $1+$2}'
5.84444
[root@oldboyedu ~]# let a=1+1
[root@oldboyedu ~]# let a=1.1+1
-bash: let: a=1.1+1: syntax error: invalid arithmetic operator (error token is ".1+1")
[root@oldboyedu ~]# echo $?
1
[root@oldboyedu ~]# expr 1 + 1
2
[root@oldboyedu ~]# echo $?
0
[root@oldboyedu ~]# expr 1.1 + 1
expr: non-integer argument
[root@oldboyedu ~]# echo $?
2
[root@oldboyedu ~]# echo 3/2 | bc
1
[root@oldboyedu ~]# echo $((2**3))
8
[root@oldboyedu ~]# let a=2**3
[root@oldboyedu ~]# echo $a
8
[root@oldboyedu ~]# let b=2**3
[root@oldboyedu ~]# echo $b
8
[root@oldboyedu ~]# expr 2 ** 3
expr: syntax error
[root@oldboyedu ~]# expr 2 * * 3
expr: syntax error
[root@oldboyedu ~]# expr 2 \** 3
expr: syntax error
[root@oldboyedu ~]# expr 2 \*\* 3
expr: syntax error
[root@oldboyedu ~]# expr "2 ** 3"
2 ** 3
[root@oldboyedu ~]# expr 2 "**" 3
expr: syntax error
[root@oldboyedu ~]# expr 2 ^ 3
expr: syntax error
[root@oldboyedu ~]# expr 2 \^ 3
expr: syntax error
[root@oldboyedu ~]# echo $[2**3]
8
[root@oldboyedu ~]# declare -i c=2**3
[root@oldboyedu ~]# echo $c
8
[root@oldboyedu ~]# echo 2**3 | bc 
(standard_in) 1: syntax error
[root@oldboyedu ~]# echo 2^3 | bc 
8
[root@oldboyedu ~]# a=1
[root@oldboyedu ~]# echo a++
a++
[root@oldboyedu ~]# echo $((a++))
1
[root@oldboyedu ~]# echo $((a++))
2
[root@oldboyedu ~]# echo $((a++))
3
[root@oldboyedu ~]# echo $((a++))
4
[root@oldboyedu ~]# a=1
[root@oldboyedu ~]# echo $((++a))
2
[root@oldboyedu ~]# echo $((++a))
3
[root@oldboyedu ~]# echo $((++a))
4
[root@oldboyedu ~]# echo $((++a))
5
[root@oldboyedu ~]# 
[root@oldboyedu ~]# a=1
[root@oldboyedu ~]# b=1
[root@oldboyedu ~]# x=a++
[root@oldboyedu ~]# y=++b
[root@oldboyedu ~]# 
[root@oldboyedu ~]# echo a
a
[root@oldboyedu ~]# echo $a
1
[root@oldboyedu ~]# echo $x
a++
[root@oldboyedu ~]# x=$((a++))
[root@oldboyedu ~]# y=$((++b))
[root@oldboyedu ~]# echo $a
2
[root@oldboyedu ~]# a=1
[root@oldboyedu ~]# b=1
[root@oldboyedu ~]# x=$((a++))
[root@oldboyedu ~]# y=$((++b))
[root@oldboyedu ~]# echo $a
2
[root@oldboyedu ~]# echo $x
1
[root@oldboyedu ~]# echo $b
2
[root@oldboyedu ~]# echo $y
2
[root@oldboyedu ~]# 8%5
-bash: 8%5: command not found
[root@oldboyedu ~]# expr 8 % 5
3
[root@oldboyedu ~]# a=8
[root@oldboyedu ~]# echo $((a%=5))
3
[root@oldboyedu ~]# echo $a
3
[root@oldboyedu ~]# echo $((a=a%5))
3


使用腳本傳參的方式實現(xiàn)整數(shù)的加、減森逮、乘榨婆、除、取余褒侧、冪運算

x=$1
y=$2

echo 1.利用'$(())'計算
echo 加:$1\+$2="$(($x+$y))"
echo 減:$1\-$2="$(($x-$y))"
echo 乘:$1\*$2="$(($x*$y))"
echo 除:$1\/$2="$(($x/$y))"
echo 冪:$1\**$2="$(($x**$y))"
echo 余:$1\%$2="$(($x%$y))"  

echo 2.利用awk計算
echo 加:$1+$2=`awk -vx=$x -vy=$y "BEGIN{print x+y}"`
echo 減:$1+$2=`awk -vx=$x -vy=$y "BEGIN{print x-y}"`
echo 乘:$1+$2=`awk -vx=$x -vy=$y "BEGIN{print x*y}"`
echo 除:$1+$2=`awk -vx=$x -vy=$y "BEGIN{print x/y}"`
echo 冪:$1+$2=`awk -vx=$x -vy=$y "BEGIN{print x**y}"`
echo 余:$1+$2=`awk -vx=$x -vy=$y "BEGIN{print x%y}"`
[root@shell scripts]# sh bc03.sh 2 6
1.利用$(())計算
加:2+6=8
減:2-6=-4
乘:2*6=12
除:2/6=0
冪:2**6=64
余:2%6=2
2.利用awk計算
加:2+6=8
減:2+6=-4
乘:2+6=12
除:2+6=0.333333
冪:2+6=64

[root@shell scripts]# cat bc02.sh 
#!/bin/bash
##############################################################
# File Name: bc03.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
x=$1
y=$2
echo="echo $1 $2"

echo 1.利用'$(())'計算
echo 加:$1\+$2="$(($x+$y))"
echo 減:$1\-$2="$(($x-$y))"
echo 乘:$1\*$2="$(($x*$y))"
echo 除:$1\/$2="$(($x/$y))"
echo 冪:$1\**$2="$(($x**$y))"
echo 余:$1\%$2="$(($x%$y))"  
echo '###################'
echo 2.利用awk計算
echo 加:$1+$2=`$echo|awk -vx=$x -vy=$y "BEGIN{print x+y}"`
echo 減:$1+$2=`$echo|awk -vx=$x -vy=$y "BEGIN{print x-y}"`
echo 乘:$1+$2=`$echo|awk -vx=$x -vy=$y "BEGIN{print x*y}"`
echo 除:$1+$2=`$echo|awk -vx=$x -vy=$y "BEGIN{print x/y}"`
echo 冪:$1+$2=`$echo|awk -vx=$x -vy=$y "BEGIN{print x**y}"`
echo 余:$1+$2=`$echo|awk -vx=$x -vy=$y "BEGIN{print x%y}"`
[root@shell scripts]# sh bc02.sh 6 3
1.利用$(())計算
加:6+3=9
減:6-3=3
乘:6*3=18
除:6/3=2
冪:6**3=216
余:6%3=0
###################
2.利用awk計算
加:6+3=9
減:6+3=3
乘:6+3=18
除:6+3=2
冪:6+3=216
余:6+3=0

表達式

條件測試表達式

image.png

image.png

image.png

image.png

文件測試表達式

image.png
[root@shell scripts]# test -L "/bin/sh" && echo ture||echo false
ture
[root@shell scripts]# test -s "/bin/sh" && echo ture||echo false
ture
[root@shell scripts]# test -d "/root" && echo ture||echo false
ture
[root@shell scripts]# test -x "ip.sh" && echo ture||echo false
ture    #文件可執(zhí)行
[root@shell scripts]# test  -x "bc.sh" && echo ture||echo false
false   #文件不可執(zhí)行
[root@shell scripts]# test ! -x "bc.sh" && echo ture||echo false
ture    #取反
[root@shell scripts]# test -s "bc.sh" && echo ture||echo false
ture    #文件存在非空
[root@shell scripts]# test ! -s "bc.sh" && echo ture||echo false
false   #取反

##############
#測試表達式
##############
[root@shell scripts]# test -f "/etc/hosts" && echo ture||echo false
ture
[root@shell scripts]# test -f "/etc/host" && echo ture||echo false
false
[root@shell scripts]# test -e "/etc/" && echo ture||echo false
ture
[root@shell scripts]# test -e "/etcetc/" && echo ture||echo false
false
[root@shell scripts]# test -d "/etc/hosts" && echo ture||echo false
false
[root@shell scripts]# test -d "/etc/" && echo ture||echo false
ture
[root@shell scripts]# test -L "/bin/sh" && echo ture||echo false
ture
[root@shell scripts]# test -L "/bin/ls" && echo ture||echo false
false
[root@shell scripts]# test -s "1.sh" && echo ture||echo false
ture
[root@shell scripts]# touch 2.sh
[root@shell scripts]# test -s "2.sh" && echo ture||echo false
false
############
#取反  
############
[root@shell scripts]# test ! -x "bc.sh" && echo ture||echo false
ture    #取反
[root@shell scripts]# test -s "bc.sh" && echo ture||echo false
ture    #文件存在非空
[root@shell scripts]# test ! -s "bc.sh" && echo ture||echo false
false   #取反

######################
#測試文件可讀可寫可執(zhí)行
######################
[root@shell scripts]# su - oldboy   #切換到普通用戶下
Last login: Thu May 16 17:01:19 CST 2019 on pts/0
[oldboy@shell ~]$ 
[oldboy@shell ~]$ test -r "test_01.sh" && echo ture||echo false
false
[oldboy@shell ~]$ test -w "test_01.sh" && echo ture||echo false
false
[oldboy@shell ~]$ test -x "test_01.sh" && echo ture||echo false
false

練習(xí)

image
image

采坑:

read讀入方式定義的變量寫為12了良风,與取參的12沖突了

[root@shell scripts]# cat testday2-1.sh 
#!/bin/bash
##############################################################
# File Name: testday2-1.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
read -p "請輸入兩個文件的路徑: " a b

[ -f $a ]&& echo $a||{
    echo "第一個文件${a}不存在"
}

[ -f $b ]&& echo $b||{
    echo "第二個文件$谊迄不存在"
    exit
}
[root@shell scripts]# sh testday2-2.sh 
請輸入兩個文件的路徑: xxx yyy
第一個文件xxx不存在
第二個文件yyy不存在
[root@shell scripts]# sh testday2-2.sh 
請輸入兩個文件的路徑: bc.sh xxx
bc.sh
第二個文件xxx不存在
[root@shell scripts]# sh testday2-2.sh 
請輸入兩個文件的路徑: xxx bc.sh
第一個文件xxx不存在
bc.sh

#2.0版 自動化
[root@shell scripts]# cat testday2-1-1.sh 
#!/bin/bash
read -p "請輸入指定文件路徑: " file   

for f in `echo $file`
do
    [ -f $f ]&&echo ${file}存在||{
    echo "${f}不存在"
}
done
[root@shell scripts]# sh 1.sh 
請輸入指定文件路徑: /server/scripts/1.sh /etc/hosts /etc/hostname
/server/scripts/1.sh /etc/hosts /etc/hostname存在
/server/scripts/1.sh /etc/hosts /etc/hostname存在
/server/scripts/1.sh /etc/hosts /etc/hostname存在


字符串測試表達式

image.png
#################
#判斷變量是否存在
#################
[root@shell ~]# a=111
[root@shell ~]# b=1111
[root@shell ~]# test "$a" = "$b" && echo ture||echo false
false
[root@shell ~]# test "$a"="$b" && echo ture||echo false
ture
[root@shell ~]# echo $a
111
[root@shell ~]# echo $b
1111

[root@shell scripts]# test -n "$a" && echo ture||echo false
ture
[root@shell scripts]# test -z "$a" && echo ture||echo false
false
[root@shell scripts]# echo $a
123
[root@shell scripts]# unset a
[root@shell scripts]# test -n "$a" && echo ture||echo false
false
[root@shell scripts]# test -z "$a" && echo ture||echo false
ture

練習(xí)

image

1. 方法第一種

#第二種
[root@shell scripts]# cat testday2-3-2.sh
#!/bin/bash
# 判斷傳入?yún)?shù)的個數(shù)
[ "$#" != "2" ] && {
    echo "參數(shù)必須為2 Usage <$0 arg1 arg2>"
        exit 1
    }

    # 判斷傳參是否為整數(shù)
    expr $1 + $2 + 1 &> /dev/null
    [ "$?" != "0" ] && {
      echo "參數(shù)必須為整數(shù)"
        exit 2
    }  

    echo -n '相加: '; echo $(($1+$2))
    echo -n '相減: '; echo $(($1-$2))
    echo -n '相乘: '; echo $(($1*$2))
    echo -n '冪運算: '; echo $(($1**$2))
    # 判斷除數(shù)是否為0
    [ "$2" = "0" ] && {
        echo "除數(shù)必須不能為0!Q萄搿统诺!"
            exit 3
        }
        echo -n '相除: '; echo $(($1/$2))
        echo -n '取余: '; echo $(($1%$2))
        [root@shell scripts]# sh testday2-3-2.sh 5 6.1
參數(shù)必須為整數(shù)
[root@shell scripts]# sh testday2-3-2.sh 5 6 7
參數(shù)必須為2 Usage <testday2-3-2.sh arg1 arg2>
[root@shell scripts]# sh testday2-3-2.sh 5 0
相加: 5
相減: 5
相乘: 0
冪運算: 1
除數(shù)必須不能為0!5醯怠篙议!
[root@shell scripts]# sh testday2-3-2.sh 6 3
相加: 9
相減: 3
相乘: 18
冪運算: 216
相除: 2
取余: 0

2.方法第二種

#第三種 read讀入默認2個參數(shù)

[root@shell scripts]# cat testday2-5.sh
#!/bin/bash
##############################################################
# File Name: testday2-5.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
read -p "請輸入需要計算的內(nèi)容:" m n

# 判斷傳參是否為整數(shù)
expr $m + $n + 1 &> /dev/null
[ "$?" != "0" ] && {
  echo "參數(shù)必須為整數(shù)"
    exit 2
}  

echo -n '相加: '; echo $(($m+$n))
echo -n '相減: '; echo $(($m-$n))
echo -n '相乘: '; echo $(($m*$n))
echo -n '冪運算: '; echo $(($m**$n))
# 判斷除數(shù)是否為0
[ "$n" = "0" ] && {
    echo "除數(shù)必須不能為0!5∨稹!"
        exit 3
    }
    echo -n '相除: '; echo $(($m/$n))
    echo -n '取余: '; echo $(($m%$n))
[root@shell scripts]# sh testday2-5.sh
請輸入需要計算的內(nèi)容:5 6 7
參數(shù)必須為整數(shù)
[root@shell scripts]# sh testday2-5.sh
請輸入需要計算的內(nèi)容:5 6.1
參數(shù)必須為整數(shù)
[root@shell scripts]# sh testday2-5.sh
請輸入需要計算的內(nèi)容:5 0
相加: 5
相減: 5
相乘: 0
冪運算: 1
除數(shù)必須不能為0R魄印O懔А!
[root@shell scripts]# sh testday2-5.sh
請輸入需要計算的內(nèi)容:4 6
相加: 10
相減: -2
相乘: 24
冪運算: 4096
相除: 0
取余: 4

整數(shù)二元比較操作符

image.png

image.png
image

查看當前磁盤/當前狀態(tài)舟误,如果使用率超過10%葡秒,則觸發(fā)報警發(fā)郵件

[root@shell scripts]# df -h|awk 'NR==2{print $(NF-1)}'
11%

[root@shell scripts]# df -h|awk 'NR==2{print $(NF-1)}'
11%
[root@shell scripts]# cat testday2-6.sh 
#!/bin/bash
##############################################################
# File Name: testday2-6.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#查看當前磁盤/當前狀態(tài),如果使用率超過10%嵌溢,則觸發(fā)報警發(fā)郵件
use=`df -h|awk 'NR==2{print $(NF-1)}'`
userNum=${use/\%/}
[ $userNum -gt 10 ] && {
    echo "shell服務(wù)器磁盤使用率超過$use"
    echo "shell服務(wù)器磁盤使用率超過$use"|mail -s "磁盤不足" 245684979@qq.com
}
[root@shell scripts]# sh testday2-6.sh
shell服務(wù)器磁盤使用率超過11%

查看內(nèi)存使用狀況眯牧,如果占用超過10%,則觸發(fā)報警

[root@shell day02]# cat testday2-7.sh 
#!/bin/bash
##############################################################
# File Name: testday2-7.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#查看內(nèi)存使用狀況赖草,如果占用超過10%学少,則觸發(fā)報警
free=`free -h|awk 'NR==2{print $3/$2*100}'`
freeNum=${free/.*/}
[ $freeNum -gt 5 ] && {
    echo "shell服務(wù)器內(nèi)存使用率超過${freeNum}%"
    echo "shell服務(wù)器內(nèi)存使用率超過${freeNum}%"|mail -s "內(nèi)存不足" 245684979@qq.com
}
[root@shell day02]# sh testday2-7.sh 
shell服務(wù)器內(nèi)存使用率超過9%


邏輯操作符

image.png
#練習(xí)查看結(jié)果
# [ -f ip.sh -a 2 -lt 3 ]&& echo 0||echo 1
0
# [ -f ip.sh -a 2 -lt 3 -a 5 -gt 6 ]&& echo 0||echo 1
1
# [ -f ip.sh -o 2 -gt 3 ]&& echo 0||echo 1
0
# [ -f ip1.sh -o 2 -gt 3 ]&& echo 0||echo 1
1
# [ ! -f ip1.sh -o 2 -gt 3 ]&& echo 0||echo 1
0
# [ -f ip.sh ] && [ 2 -lt 3 ] && [ 2 -lt 3 ]&&echo 0||echo 1
0
# [ -f ip.sh ] && [ 2 -lt 3 ] && [ 2 -eq 3 ]&&echo 0||echo 1
1
# [ -f ip.sh ] && [ 2 -lt 3 ] && [ 2 -lt 3 ]&&echo 0||echo 1
0
# [[ -f ip.sh ]] && [[ 2 -lt 3 ]] && [[ 3 -gt 2 ]]&&echo 0||echo 1
0


練習(xí)

image

1、 輸入或者通過命令傳入一個字符或者數(shù)字秧骑,如果傳入的數(shù)字等于1就打印1版确,如果等于2就打印2;如果不等于1也不等于2乎折,就提示輸入不對绒疗,然后退出程序。(兩種比較方式任選其一:數(shù)字比較或字符串比較)

[root@shell day02]# cat testday2-10.sh 
#!/bin/bash
##############################################################
# File Name: testday2-10.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################

read -p "請輸入一個字符或者數(shù)字:" a

[ $a -eq 1 ]&& {
    echo $a
    exit 0
}||
[ $a -eq 2 ]&& {
    echo $a 
    exit 0
}||
    echo 輸入錯誤!
    exit 1
}

#[ $a -ne 1 -a $a -ne 2 ]&& echo 輸入錯誤!
[root@shell day02]# sh testday2-10.sh 
請輸入一個字符或者數(shù)字:1
1
[root@shell day02]# sh testday2-10.sh 
請輸入一個字符或者數(shù)字:2
2
[root@shell day02]# sh testday2-10.sh 
請輸入一個字符或者數(shù)字:3
輸入錯誤!

2骂澄、 開發(fā)shell腳本吓蘑,分別以腳本傳參方式和read讀入方式比較兩個整數(shù)大小,用條件表達式(禁止if)進行判斷并以屏幕輸出的方式提醒用戶比較結(jié)果坟冲。(一共需要開發(fā)2個腳本磨镶,在傳參和read讀入方式實現(xiàn)時,需要對變量是否為數(shù)字及傳參個數(shù)是否正確給予提示)

1)判斷是否是兩個參數(shù)

2)判斷是否為整數(shù)

3)[ 2 -gt 3 ] && echo “2大于3”|| echo “2等于3”|| echo “2小于3“

第一種read讀入方式

[root@shell scripts]# cat testday2-8.sh
#!/bin/bash
#read讀入方式
read -p "請輸入兩個整數(shù): " a b
#判斷是否為整數(shù)
expr $a + $b &> /dev/null
[ $? -eq 0 ]&& echo 參數(shù)正確!||{
    echo "參數(shù)必須為整數(shù)"
    exit 2
}
[ $a -gt $b ]&& {
    echo "數(shù)值對比: [$a] > [$b]"
}||{
[ $a -lt $b ]&& {
    echo "數(shù)值對比: [$a] < [$b] "
}||{
[ $a -eq $b ]&& {
        echo "數(shù)值對比: [$a] = [$b]"
        }
    }
}
[root@shell scripts]# sh testday2-8.sh
請輸入兩個整數(shù): 5 6
參數(shù)正確!
數(shù)值對比: [5] < [6] 
[root@shell scripts]# sh testday2-8.sh
請輸入兩個整數(shù): 8 1
參數(shù)正確!
數(shù)值對比: [8] > [1]
[root@shell scripts]# sh testday2-8.sh
請輸入兩個整數(shù): 8 8
參數(shù)正確!
數(shù)值對比: [8] = [8]
[root@shell scripts]# sh testday2-8.sh
請輸入兩個整數(shù): 2.1 1
參數(shù)必須為整數(shù)

第二種傳參方式

[root@shell scripts]# cat testday2-9.sh 
#!/bin/bash
#傳參方式
#判斷是否是兩個參數(shù)
[ $# -ne 2 ]&&{
    echo "請輸入兩個參數(shù)進行對比!"
    exit
}
#判斷是否為整數(shù)
expr $1 + $2 &> /dev/null
[ $? -eq 0 ]&& echo 參數(shù)正確!||{
    echo "參數(shù)必須為整數(shù)"
    exit 
}
#數(shù)值對比
[ $1 -gt $2 ]&& {
    echo "數(shù)值對比: [$1] > [$2]"
}
[ $1 -lt $2 ]&& {
    echo "數(shù)值對比: [$1] < [$2] "
}
[ $1 -eq $2 ]&& {
    echo "數(shù)值對比: [$1] = [$2]"
}
[root@shell scripts]# sh testday2-9.sh 8 8
參數(shù)正確!
數(shù)值對比: [8] = [8]
[root@shell scripts]# sh testday2-9.sh 8 6
參數(shù)正確!
數(shù)值對比: [8] > [6]
[root@shell scripts]# sh testday2-9.sh 6 8
參數(shù)正確!
數(shù)值對比: [6] < [8] 
[root@shell scripts]# sh testday2-9.sh 6 8.1
參數(shù)必須為整數(shù)

3樱衷、 打印菜單棋嘲,按照選擇項選擇你喜歡的美女

示例菜單:

[root@oldboy scripts]# sh meinv.sh

1.heijiajia

2.高圓圓

3.蔡徐坤

please input the num you like: 

要求:

1)當用戶輸入1時,輸出“I guess you like heijiajia”矩桂,然后退出腳本

2)當用戶輸入非1-3的字符時沸移,輸出“I guess you are not man”,然后退出腳本

[root@shell scripts]# cat caidan.sh 
#!/bin/bash
prefix="I guess you like "

#菜單
cat <<EOF
    1.heijiajia
    2.高圓圓
    3.蔡徐坤
EOF

read -p "please input the num you like: " num
[ $num -eq "1" ] && {
    echo "$prefix"heijiajia
}
[ $num -eq "2" ] && {
    echo "$prefix"高圓圓
}
[ $num -eq "3" ] && {
    echo "打籃球那個 Are You OK??"
}

#echo -e "\t1.heijiajia\n\t2.gaoyuanyuan\n\t3.caixukun"

[root@shell scripts]# sh caidan.sh 
    1.heijiajia
    2.高圓圓
    3.蔡徐坤
please input the num you like: 1
I guess you like heijiajia
[root@shell scripts]# sh caidan.sh 
    1.heijiajia
    2.高圓圓
    3.蔡徐坤
please input the num you like: 2
I guess you like 高圓圓
[root@shell scripts]# sh caidan.sh 
    1.heijiajia
    2.高圓圓
    3.蔡徐坤
please input the num you like: 3
打籃球那個 Are You OK??


Shell練習(xí)作業(yè)

1.檢查OSPF route-ID配置痪伦,配置如下,請用shell編寫代碼雹锣,條件如下:

檢查OSPF route-ID配置网沾,配置如下,請用shell編寫代碼蕊爵,條件如下:
1辉哥、檢查ospf的route-id值
2、route-id值必須與interface LoopBack0的IP地址值相同
grep -A 1 "interface LoopBack0" 3.txt | sed -n '$p' | awk '{print $3}
3攒射、如果兩個值不相等醋旦,或ospf的route-id值不以139開頭,則打印出route-id的值
ofpf 100
route-id 139.11.0.1
 area 0.0.0.0
    network 139.11.0.1 0.0.0.0
    network 140.11.0.0 0.0.0.3
    network 140.11.0.8 0.0.0.3
    network 140.11.0.16 0.0.0.3
network 140.11.0.24 0.0.0.3
network 140.11.0.32 0.0.0.3
#
interface LoopBack0
 ip address 139.11.0.1 255.255.255.255
#

image
image
[root@shell day02]# vim zuoye01.sh 
  1 #!/bin/bash                                                                                    
  2 ##############################################################
  3 # File Name: zuoye01.sh
  4 # Version: V1.0
  5 # Author: lcx
  6 # Organization: www.oldboyedu.com
  7 ##############################################################
  8 #ospf route-ID配置文件路徑/server/scripts/day02/3.txt
  9 dir=/server/scripts/day02/3.txt
 10 routeID=`cat $dir |awk 'NR==2{print $2}'`
 11 interfaceIP=`grep -A 1 "interface LoopBack0" $dir|awk 'NR==2{print $3}'`
 12 routeIPhead=`cat $dir |awk -F"[ .]+" 'NR==2{print $2}'`
 13 head="139"
 14 #檢查ospf的route-id值
 15 echo "osps的route-id為: $routeID"
 16 #檢查route-id與interface LoopBack0IP是否相同
 17 [ "$routeID" != "$interfaceIP" ]&&{
 18     echo "1.IP與ID不相等 IP為:$interfaceIP ID為$routeID"
 19 }
 20 [ "$routeIPhead" != "139" ]&&{
 21     echo "2.route-id的值不是139開頭 routeID為:$routeID"
 22 }                                                                  
[root@shell day02]# sh zuoye01.sh 
osps的route-id為: 239.11.0.1
1.IP與ID不相等 IP為:139.11.0.1 ID為239.11.0.1
2.route-id的值不是139開頭 routeID為:239.11.0.1
[root@shell day02]# sh zuoye01.sh 
osps的route-id為: 139.11.0.1

2.處理以下文件內(nèi)容会放,將域名提取并進行計數(shù)排序饲齐,如處理:

處理以下文件內(nèi)容,將域名提取并進行計數(shù)排序咧最,如處理:
http://www.baidu.com/index.html
http://www.baidu.com/1.html
http://post.baidu.com/index.html
http://mp3.baidu.com/index.html
http://www.baidu.com/3.html
http://post.baidu.com/2.html
得到如下結(jié)果:
域名的出現(xiàn)次數(shù)  域名
3   www.baidu.com
2   post.baidu.com
1   mp3.baidu.com

思路:

image
[root@shell day02]# cat 4.txt |awk -F'[/]' '{print $3}'|sort|uniq -c|sort -rn|sed '1i域名的出現(xiàn)次數(shù)  域名'
域名的出現(xiàn)次數(shù)  域名
      3 www.baidu.com
      2 post.baidu.com
      1 mp3.baidu.com

3.打印菜單捂人,按照選擇項一鍵安裝不同的web服務(wù)

打印菜單,按照選擇項一鍵安裝不同的web服務(wù)
示例菜單:
[root@oldboy scripts]# sh menu.sh
 1.[install lnmp]
 2.[install lamp]
 3.[exit]
please input the num you want: 
 要求:
 1)當用戶輸入1時矢沿,輸出“start installing lamp提示”滥搭,然后執(zhí)行/server/scripts/lamp.sh,(執(zhí)行方式使用全路徑方式執(zhí)行)。
   腳本內(nèi)容輸出“l(fā)amp is installed”并退出腳本捣鲸,此為工作中的一鍵安裝lamp腳本
 2)當用戶輸入2時瑟匆,輸出“start installing lnmp提示”,然后執(zhí)行/server/scripts/lnmp.sh, (執(zhí)行方式使用 全路徑方式執(zhí)行)摄狱。
  腳本內(nèi)容輸出“l(fā)nmp is installed”并退出腳本脓诡,此為工作中的一鍵安裝lnmp腳本
 3)當輸出3時,退出當前菜單及腳本  
 4)當用戶輸入非1-3的字符時媒役,輸出“Input Error”,然后退出腳本
 5)對執(zhí)行的腳本進行相關(guān)的條件判斷祝谚,例如:腳本是否存在,是否可執(zhí)行等操作酣衷,盡量使用今天講的知識點

image
#技術(shù)水平有限交惯,不求精簡只求實現(xiàn)

[root@shell day02]# cat zuoye02.sh 
#!/bin/bash
##############################################################
# File Name: zuoye02.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#檢測腳本是否存在且非空,是否可執(zhí)行
file1=`[ -s /server/scripts/lamp.sh ]&& echo ture||echo fluse`
file2=`[ -s /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
exec1=`[ -x /server/scripts/lamp.sh ]&& echo ture||echo fluse`
exec2=`[ -x /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
[ $file1 = "ture" ]&& echo lamp.sh腳本文件存在且非空||{
    echo "lamp.sh腳本文件不存在或是一個空文件!!!"
    }&&{
    [ $exec1 = "ture" ]&& echo lamp.sh腳本文件可以執(zhí)行||{
        echo "lamp.sh腳本文件不可執(zhí)行!!!"
    }&&{
    [ $file2 = "ture" ]&& echo lnmp.sh腳本文件存在且非空||
        echo -eq "lnmp.sh腳本文件不存在或是一個空文件!!!"
    }&&{
    [ $exec2 = "ture" ]&& echo lnmp.sh腳本文件可以執(zhí)行||{
        echo "lnmp.sh腳本文件不可執(zhí)行!!!"
        exit
       }
    }
}
#打印菜單穿仪,按照選擇項一鍵安裝不同的web服務(wù)
cat <<EOF
    1.[install lnmp]
    2.[install lamp]
    3.[exit]
EOF

read -p "please input the num you want:" num
#安裝lamp環(huán)境
[ $num -eq "1" ] &&{
    echo "start installing LAMP"
    sleep 1
    /server/scripts/lamp.sh
    exit
    }||{
    [ $num -eq "2" ] &&{
        echo "start installing LNMP"
        sleep 1
        /server/scripts/lnmp.sh
        exit
        }
    }||{
    [ $num -eq "3" ] &&{
        echo "即將退出腳本..."
        sleep 1
        exit
        }
    }||{
    [ $num != "{1..3}" ]&&{
        echo "Input Error錯誤!"
        exit
    }
}

測試結(jié)果

image
image
image
image

if語句

if條件語句席爽,簡單來說,其語義類似于漢語中的“如果...那么...”啊片。if語句是Linux運維人員在實際生產(chǎn)過程中使用的最頻繁也是最重要的語句只锻。因此,務(wù)必重視if條件語句的知識紫谷,并牢固掌握齐饮。

單分支

image

雙分支

image

多分支

image

練習(xí)題—1

image
image
[root@shell init.d]# pwd
/etc/init.d
[root@shell init.d]# cat rsyncd 
#!/bin/bash
#如果參數(shù)是start則啟動start rsync --daemon
if [ "$1" = "start" ];then
    rsync --daemon
    sleep 1
    echo "rsync服務(wù)啟動成功"
fi
#如果參數(shù)是stop則關(guān)閉--pkill rsync
if [ "$1" = "stop" ];then
    #查看當前rsync進程是否存在,非0則存在
    if [ `ss -lntup|grep rsync|wc -l` -eq 0 ];then
        echo "rsync處于關(guān)閉狀態(tài)"
    else
        sleep 1
        pkill rsync
    fi
fi
#如果是restart則先執(zhí)行stop再執(zhí)行start
if [ "$1" = "restart" ];then
    #先關(guān)閉
    if [ `ss -lntup|grep rsync|wc -l` -eq 0 ];then
        echo "rsync處于關(guān)閉狀態(tài)"
    else
        sleep 1
        pkill rsync
    fi
    #再次啟動
    rsync --daemon
    echo "rsync服務(wù)重啟成功"
fi
[root@shell init.d]# ss -lntup|grep rsync
[root@shell init.d]# sh rsyncd start
rsync服務(wù)啟動成功
[root@shell init.d]# ss -lntup|grep rsync
tcp    LISTEN     0      5         *:873                   *:*                   users:(("rsync",pid=10519,fd=4))
tcp    LISTEN     0      5        :::873                  :::*                   users:(("rsync",pid=10519,fd=5))
[root@shell init.d]# sh rsyncd stop
[root@shell init.d]# ss -lntup|grep rsync
[root@shell init.d]# sh rsyncd restart
rsync處于關(guān)閉狀態(tài)
rsync服務(wù)重啟成功
[root@shell init.d]# ss -lntup|grep rsync
tcp    LISTEN     0      5         *:873                   *:*                   users:(("rsync",pid=10538,fd=4))
tcp    LISTEN     0      5        :::873                  :::*                   users:(("rsync",pid=10538,fd=5))

#絕對路徑執(zhí)行方法
需要添加執(zhí)行權(quán)限
[root@shell ~]# /etc/init.d/rsyncd restart
[root@shell ~]# /etc/init.d/rsyncd stop
[root@shell ~]# /etc/init.d/rsyncd start

練習(xí)題—2

判斷nginx是否活著捐寥,如果沒有活著就打印“郵件報警”(判斷依據(jù):curl/wget訪問url)
#取狀態(tài)碼的值
curl -sw "%{http_code}\n" -o /dev/null 127.0.0.1
curl -I 127.0.0.1 2>/dev/null|grep -o 200

image
image
[root@shell day03]# cat zuoye03.sh
#!/bin/bash
##############################################################
# File Name: zuoye03.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#判斷nginx是否活著,如果沒有活著就打印“郵件報警
curl -I 127.0.0.1 2>/dev/null|grep -o 200
if [ $? = 0 ];then
    echo Nginx服務(wù)處于運行狀態(tài)
else
    echo -e "警告祖驱!\n\tNginx服務(wù)處于關(guān)閉狀態(tài)"
    echo -e "一級警告:\n\tNginx服務(wù)處于關(guān)閉狀態(tài),網(wǎng)站可能宕機,請盡快處理!"|mail -s "Nginx服務(wù)報警" 245684979@qq.com
fi


練習(xí)題—3

image

函數(shù)

image

函數(shù)名的定義規(guī)則和變量是一樣:數(shù)字握恳、字母、下劃線捺僻、但是不能以數(shù)字開頭

寫函數(shù)的三種方法

[root@shell day04]# cat test1.sh
#!/bin/bash
##############################################################
# File Name: test1.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#第一種方法
#定義函數(shù),函數(shù)加載到內(nèi)存
function hello(){
    echo "hello oldchang"
    # return n
}
#使用函數(shù)
hello

#第二種方法
function hello2 {
    echo "hello2 2oldboychang"
}
hello2

#第三種方法
hello3(){
    echo "hello3 3oldoychang"
}
hello3
[root@shell day04]# sh test1.sh
hello oldchang
hello2 2oldboychang
hello3 3oldoychang

可以在函數(shù)下一起調(diào)用

優(yōu)先調(diào)用函數(shù)


[root@shell day04]# touch hello
[root@shell day04]# chmod +x hello 
[root@shell day04]# echo hello >hello 
[root@shell day04]# ll
total 8
-rwxr-xr-x 1 root root   6 Jul 18 10:00 hello
-rw-r--r-- 1 root root 501 Jul 18 09:57 test1.sh
[root@shell day04]# 
[root@shell day04]# source /server/scripts/day04/test1.sh 
hello oldchang
hello2 2oldboychang
hello3 3oldoychang
[root@shell day04]# hello   #優(yōu)先調(diào)用了函數(shù)
hello oldchang  

函數(shù)的退出狀態(tài)碼

腳本的退出狀態(tài)碼乡洼,使用exit定義,之后腳本退出

函數(shù)的退出狀態(tài)碼匕坯,使用return定義束昵,之后函數(shù)退出

[root@shell day04]# vim test1.sh 
  1 #!/bin/bash                                                                 
  2 ##############################################################
  3 # File Name: test1.sh
  4 # Version: V1.0
  5 # Author: lcx
  6 # Organization: www.oldboyedu.com
  7 ##############################################################
  8 #
  9 #
 10 function hello(){
 11     if [ -f "/etc/hosts" ];then
 12         echo "文件存在"
 13     else
 14         return 2
 15     fi
 16 }
 17 hello
 18 echo $?
[root@shell day04]# sh test1.sh 
文件存在
0

帶參數(shù)的函數(shù)

image
[root@shell day04]# vim test2.sh 
  1 #!/bin/bash
  2 function hello {
  3     echo "hello $1"
  4 }
  5 hello $1
[root@shell day04]# sh test2.sh oldboy
hello oldboy

[root@shell day04]# vim test2.sh 
  1 #!/bin/bash
  2 function hello {
  3    echo "hello $1 $2"   #定義2個參數(shù)
  4 }                                                                           
  5 hello $1 $2
[root@shell day04]# sh test2.sh oldboy oldchang
hello oldboy oldchang

image

位置函數(shù)

[root@shell day04]# cat test3.sh 
#!/bin/bash
function hello {
   echo "hello $*"
}
hello $# $1 "$*"
[root@shell day04]# sh test3.sh 1 2 3
hello 3 1 1 2 3

第二種方法,也是最常用的方法

[root@shell day04]# cat test3.sh 
#!/bin/bash
function hello {
   echo "腳本名稱: $0"
   echo "函數(shù)的參數(shù)個數(shù): $#"
   echo "第一個參數(shù): $1"
   echo "顯示所有參數(shù): $*"
   echo "執(zhí)行狀態(tài)碼: $?"
}
hello $*
[root@shell day04]# sh test3.sh 1 2 3 4 5
腳本名稱: test3.sh
函數(shù)的參數(shù)個數(shù): 5
第一個參數(shù): 1
顯示所有參數(shù): 1 2 3 4 5
執(zhí)行狀態(tài)碼: 0

image

case語句

image
image
image

case條件語句練習(xí)

image
[root@shell day04]# cat case1.sh
#!/bin/bash
##############################################################
# File Name: case1.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
case "$1" in
    "start"|"START")
        echo "已啟動"
        ;;
    "stop"|"STOP")
        echo "已停止"
        ;;
    *)
        echo "你tm說的啥"
esac
 [root@shell day04]# sh case1.sh start
已啟動
[root@shell day04]# sh case1.sh stop
已停止
[root@shell day04]# sh case1.sh xxx
你tm說的啥
[root@shell day04]# sh case1.sh START
已啟動
[root@shell day04]# sh case1.sh STOP
已停止

練習(xí)題

image

練習(xí)

image
image

使用case判斷是數(shù)字還是字母

編寫腳本醒颖,使用單個字符進行傳參妻怎,使用case判斷是數(shù)字還是字母

[root@shell day04]# cat case2.sh 
#!/bin/bash
##############################################################
# File Name: case1.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
case "$1" in
    [0-9])
        echo "這是數(shù)字$1"
        ;;
    [a-Z])
        echo "這是字母$1"
        ;;
    *)
        echo "你tm輸?shù)纳?
        exit
esac

[root@shell day04]# sh case2.sh v
這是字母v
[root@shell day04]# sh case2.sh A
這是字母A
[root@shell day04]# sh case2.sh 5
這是數(shù)字5
[root@shell day04]# sh case2.sh 0
這是數(shù)字0

將” 打印菜單修改成case或if語句

將” 打印菜單,按照選擇項一鍵安裝不同的web服務(wù)”腳本,將其中的條件表達式修改成case或if語句**

#case語句

[root@shell day04]# cat web.sh 
#!/bin/bash
##############################################################
# File Name: zuoye02.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#檢測腳本是否存在且非空泞歉,是否可執(zhí)行
file1=`[ -s /server/scripts/lamp.sh ]&& echo ture||echo fluse`
file2=`[ -s /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
exec1=`[ -x /server/scripts/lamp.sh ]&& echo ture||echo fluse`
exec2=`[ -x /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
case "$file1" in
    ture)
        echo -e "\033[32mlamp.sh腳本文件存在且非空\033[0m"
        ;;
    *)
        echo -e "\033[31mlamp.sh腳本文件不存在或是一個空文件!!!\033[0m"
    esac
case "$exec1" in
    ture)
        echo -e "\033[32mlamp.sh腳本文件可以執(zhí)行\(zhòng)033[0m"
        ;;
    *)
        echo -e "\033[31mlamp.sh腳本文件不可執(zhí)行!!!\033[0m"
    esac
case "$file2" in
    ture)
        echo -e "\033[32mlnmp.sh腳本文件存在且非空\033[0m"
        ;;
    *)
        echo -e "\033[31mlnmp.sh腳本文件不存在或是一個空文件!!!\033[0m"
    esac
case "$exec2" in
    ture)
        echo -e "\033[32mlnmp.sh腳本文件可以執(zhí)行\(zhòng)033[0m"
        ;;
    *)
        echo -e "\033[31mlnmp.sh腳本文件不可執(zhí)行!!!\033[0m"
esac
#打印菜單,按照選擇項一鍵安裝不同的web服務(wù)
cat << EOF
    `echo -e "\033[35m (1).[install lamp]\033[0m"`
    `echo -e "\033[36m (2).[install lnmp]\033[0m"`
    `echo -e "\033[33m (3).[exit]\033[0m"`
EOF

read -p "please input the num you want:" num
#安裝lamp與lnmp環(huán)境
case "$num" in
    1)
        echo start installing LAMP
        sleep 1
        /server/scripts/lamp.sh
        exit
        ;;
    2)
        echo start installing LNMP
        sleep 1
        /server/scripts/lnmp.sh
        exit
        ;;
    3)
        echo 即將退出腳本...
        sleep 1
        exit
        ;;
    *)
        echo Input Error輸入不識別!,啟動自毀程序...
        sleep 2
        echo 再見人類......
        sleep 2
        exit
esac

image
#  if語句

[root@shell day04]# cat /server/scripts/day03/zuoye02.sh 
#!/bin/bash
##############################################################
# File Name: zuoye02.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#檢測腳本是否存在且非空匿辩,是否可執(zhí)行
file1=`[ -s /server/scripts/lamp.sh ]&& echo ture||echo fluse`
file2=`[ -s /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
exec1=`[ -x /server/scripts/lamp.sh ]&& echo ture||echo fluse`
exec2=`[ -x /server/scripts/lnmp.sh ]&& echo ture||echo fluse`
if [ $file1 = "ture" ];then
        echo "lamp.sh腳本文件存在且非空"
    else 
        echo "lamp.sh腳本文件不存在或是一個空文件!!!"
    fi
if [ $exec1 = "ture" ];then
        echo lamp.sh腳本文件可以執(zhí)行
    else
        echo lamp.sh腳本文件不可執(zhí)行!!!
    fi
if [ $file2 = "ture" ];then
        echo lnmp.sh腳本文件存在且非空
    else
        echo lnmp.sh腳本文件不存在或是一個空文件!!!
    fi
if [ $exec2 = "ture" ];then
        echo lnmp.sh腳本文件可以執(zhí)行
    else
        echo lnmp.sh腳本文件不可執(zhí)行!!!
        exit
    fi
#打印菜單腰耙,按照選擇項一鍵安裝不同的web服務(wù)
cat << EOF
    `echo -e "\033[35m (1).[install lamp]\033[0m"`
    `echo -e "\033[36m (2).[install lnmp]\033[0m"`
    `echo -e "\033[34m (3).[exit]\033[0m"`
EOF

read -p "please input the num you want:" num
#安裝lamp環(huán)境
if [ $num = "1" ];then
    echo start installing LAMP
    sleep 1
    /server/scripts/lamp.sh
    exit
elif [ $num = "2" ];then
    echo start installing LNMP
    sleep 1
    /server/scripts/lnmp.sh
    exit
elif [ $num = "3" ];then
    echo 即將退出腳本...
    sleep 1
    exit
elif [ $num != "{1..3}" ];then
    echo Input Error輸入不識別!,啟動自毀程序...
    sleep 2
    echo 再見人類......
    sleep 2
    exit
fi

將Nginx服務(wù)改為case方式+函數(shù)方式

將Nginx服務(wù)管理腳本改為case方式+函數(shù)方式,并通過systemctl進行控制啟動停止

先將nginx編譯好

yum install -y gcc-c++ pcre-devel zlib-devel    #下載依賴
tar xf nginx-1.17.1.tar #解壓到當前目錄
cd nginx-1.17.1/    #切換到解壓后的目錄下
./configure --prefix=/usr/local/nginx   #路徑隨意
make && make install

[root@shell ~]# ll /usr/local/nginx/sbin/nginx 
-rwxr-xr-x 1 root root 3830336 Jul 18 09:19 /usr/local/nginx/sbin/nginx
[root@shell ~]# cd /etc/init.d/
[root@shell init.d]# touch nginx
[root@shell init.d]# chmod +x nginx

if方式+函數(shù)方式

[root@shell init.d]# vim nginx  #
#!/bin/bash
##############################################################
# File Name: nginx.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
if [ "$1" = "start" ];then
    nginx
    echo "nginx服務(wù)啟動成功"
fi
if [ "$1" = "stop" ];then
#查看當前nginx進程是否存在,非0則存在
    if [ `ss -lntup|grep nginx|wc -l` -eq 0 ];then
        echo "nginx處于關(guān)閉狀態(tài)"
    else
        pkill nginx
    fi
fi
if [ "$1" = "restart" ];then
#先關(guān)閉
    if [ `ss -lntup|grep nginx|wc -l` -eq 0 ];then
        echo "nginx處于關(guān)閉狀態(tài)"
    else
        pkill nginx
        sleep 1
    fi
    nginx
    echo "nginx服務(wù)重啟成功"
fi

case方式+函數(shù)方式

#為nginx添加systemd啟動文件
[root@shell init.d]# cd /usr/lib/systemd/system
[root@shell system]# cat nginx_oldboy.service 
[Unit]
Description=nginx service
After=nginx_oldboy.target

[Service]
Type=forking
ExecStart=/etc/init.d/nginx start
ExecReload=/etc/init.d/nginx restart
ExecStop=/etc/init.d/nginx stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target

#檢查是否可以啟動關(guān)閉重啟
[root@shell system]# ss -lntup|grep nginx
[root@shell system]# systemctl start nginx_oldboy.service   #啟動
[root@shell system]# ss -lntup|grep nginx
tcp    LISTEN     0      128       *:80                    *:*                   users:(("nginx",pid=15894,fd=6),(nginx",pid=15893,fd=6))
[root@shell system]# systemctl stop nginx_oldboy.service    #關(guān)閉
[root@shell system]# ss -lntup|grep nginx
[root@shell system]# systemctl restart nginx_oldboy.service     #重啟
[root@shell system]# ss -lntup|grep nginx
tcp    LISTEN     0      128       *:80                    *:*                   users:(("nginx",pid=15926,fd=6),(nginx",pid=15925,fd=6))

使用case選擇水果,打印水果名及其顏色

使用case選擇水果铲球,并打印水果名及其顏色

#給到的要求與條件
  1.apple
  2.pear
  3.banana
  4.blueberry
其中挺庞,顏色表達式分別為
31m 紅色
32m 綠色
33m 黃色
34m 藍色
使用方式為
[root@oldboy-node101 ~]# echo -e "\E[1;31m我是紅色 \E[0m"
我是紅色 
[root@oldboy-node101 ~]# echo -e "\E[1;32m我是綠色 \E[0m"
我是綠色 
[root@oldboy-node101 ~]# echo -e "\E[1;33m我是黃色 \E[0m"
我是黃色 
[root@oldboy-node101 ~]# echo -e "\E[1;34m我是藍色 \E[0m"
我是藍色
1)打印菜單
2)使用read,顯示一句話“選擇你喜歡的水果”
3)使用case判斷數(shù)字是【1|2|3|4】
4)如果都不符合稼病,報錯退出

while循環(huán)

image

while語法

image
image

while按行讀入文件

image

練習(xí)

1.while循環(huán)從1加到100选侨,然后再額外使用兩種方式計算

2.while循環(huán)讀入數(shù)據(jù),計算文件內(nèi)的年齡平均值

3.將第6章的練習(xí)1然走,改為死循環(huán)的形式援制。菜單中加入選項exit,只有輸入exit才能退出

1.while循環(huán)從1加到100芍瑞,然后再額外使用兩種方式計算

[root@shell day04]# cat while3.sh
#!/bin/bash
##############################################################
# File Name: while3.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#while循環(huán)從1加到100晨仑,然后再額外使用兩種方式計算
a=0
while [ $a -lt 100 ];do
    let a++
    echo $a
done
[root@shell day04]# sh while3.sh
1
2
3
4
...
100

#第二種
[root@shell day04]# echo "(1+100)*100/2"|bc
5050

2.while循環(huán)讀入數(shù)據(jù),計算文件內(nèi)的年齡平均值

[root@shell day04]# cat age.txt 
jiaojiao 20
yingqian 20
jiangyuan 25
xiaolu 30
xuxu 18
dingsheng 38
lili 5
[root@shell day04]# cat while4.sh 
#!/bin/bash
##############################################################
# File Name: while3.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#計算平均年齡,文件是/server/scripts/age.txt
#a=echo `cat age.txt|awk '{print $2}'`
sum=0
count=0
while read line;do
    age=`echo $line|awk '{print $2}'`
    let sum=${sum}+${age}
    let count++
done  < $1
echo "$sum/$count"|bc
[root@shell day04]# sh while4.sh age.txt
22

3.將第6章的練習(xí)1拆檬,改為死循環(huán)的形式洪己。菜單中加入選項exit,只有輸入exit才能退出

[root@shell day04]# cat caidan.sh 
#!/bin/bash
#打印菜單竟贯,按照選擇項選擇你喜歡的人物
prefix="I guess you like "
#菜單
while true ;do
cat << EOF
    `echo -e "\033[32m 1.棋王\033[0m"`
    `echo -e "\033[33m 2.女神\033[0m"`
    `echo -e "\033[34m 3.娘炮\033[0m"`
    `echo -e "\033[35m 4.鐵人\033[0m"`
    `echo -e "\033[36m 5.退出\033[0m"`
EOF
read -p "please input the num you like: " num
if [ $num = "1" ];then
        echo "$prefix"黑嘉嘉
    elif [ $num = "2" ];then
        echo "$prefix"高圓圓
    elif [ $num = "3" ];then
        echo "$prefix"打籃球的那個蔡徐坤? Are You OK??
    elif [ $num = "4" ];then
        echo "$prefix"鹿晗...
    elif [ $num = "5" ];then
        echo "即將退出..."
        sleep 1
        exit
    else
        echo "輸入錯誤!請重新輸入"
    fi
done

image

練習(xí)

image

1答捕、猜數(shù)字游戲:

首先讓系統(tǒng)隨機生成一個數(shù)字,給這個數(shù)字定一個范圍屑那,讓用戶輸入猜的數(shù)字拱镐,對輸入的數(shù)字進行判斷艘款,如果不符合要求,就給與高或低的提示痢站,猜對后給出猜對用的次數(shù)磷箕,請用while語句實現(xiàn)。

image
image.png

RANDOM%99+1)) 0到100隨機數(shù)字

[root@shell lianxi]# cat 2.1.sh 
#!/bin/bash
##############################################################
# File Name: 2.1.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#定義輸入的次數(shù)
total=0
#定義字符集
export LANG="zh_CH.UTF-8"
#生成0到100隨機數(shù)字并清除
num=$((RANDOM%101))
echo "生成隨機數(shù)為$num"
echo "============================"
usleep 100000
clear
echo "客官~猜一猜我奶奶多大年齡了?
      請輸入[1-100]的整數(shù)"
#定義檢測輸入值的函數(shù)age

age(){
    read -p "客官~請輸入你猜的年齡: " num1
    #判斷是否為整數(shù)
    expr $num1 + 1 &>/dev/null
    if [ $? -ne 0 ];then
        echo "(⊙o⊙)…輸入格式錯了呢~客官"
        age
    fi
}
#定義輸入值反饋函數(shù)
point(){
    #調(diào)用total累計客官輸入次數(shù)
    ((total++))
    if [ $num1 -eq $num ];then
        echo "客官~您真是個天才!恭喜您獲得奶奶一車"
        echo "我奶奶今年${num}歲"
        echo 一共猜了${total}次
        exit 0
    elif [ $num1 -gt $num ];then
        echo "客官~我奶奶老年輕了阵难!您猜的太大了"
        echo "再來一次!加油~: "
        age
    elif [ $num1 -lt $num ];then
        echo "客官~我奶奶比我大岳枷!您猜的太小了"
        echo "再來一次!加油~"
        age
    fi
}
#定義循環(huán)此腳本函數(shù),猜對年齡后退出,猜錯則從point函數(shù)中調(diào)用age函數(shù)繼續(xù)猜
main(){
    age
    while true
    do
        point
    done
}
main
[root@shell lianxi]# sh 2.1.sh 
生成隨機數(shù)為58
============================
客官~猜一猜我奶奶多大年齡了?
      請輸入[1-100]的整數(shù)
客官~請輸入你猜的年齡: 50
客官~我奶奶比我大!您猜的太小了
再來一次!加油~
客官~請輸入你猜的年齡: 80
客官~我奶奶老年輕了呜叫!您猜的太大了
再來一次!加油~
客官~請輸入你猜的年齡: 60
客官~我奶奶老年輕了空繁!您猜的太大了
再來一次!加油~
客官~請輸入你猜的年齡: 55
客官~我奶奶比我大!您猜的太小了
再來一次!加油~
客官~請輸入你猜的年齡: 57
客官~我奶奶比我大朱庆!您猜的太小了
再來一次!加油~
客官~請輸入你猜的年齡: 58
客官~您真是個天才!恭喜您獲得奶奶一車
我奶奶今年58歲
一共猜了6次

2.使用if和while實現(xiàn)菜單系統(tǒng)信息案例:

? h 顯示命令幫助 sleep 2刷新菜單

? f 顯示登錄信息 who

? d 顯示磁盤掛載 fdisk -l

? m 查看內(nèi)存使用 free -h

? u 查看系統(tǒng)負載 uptime

? q 退出程序

[root@shell lianxi]# cat menu.sh 
#!/bin/bash
##############################################################
# File Name: menu.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
export LANG="zh_CH.UTF-8"
user=`who|wc -l`
free1=`free -h|awk 'NR==2{print $3/$2*100}'`
free2=${free1/.*/}
uptime=`uptime|awk '{print $NF}'`
while true ;do
cat << EOF
    `echo -e "\033[32m [h].顯示命令幫助\033[0m"`
    `echo -e "\033[32m [f].顯示登錄信息\033[0m"`
    `echo -e "\033[32m [d].顯示磁盤掛載\033[0m"`
    `echo -e "\033[32m [m].查看內(nèi)存使用\033[0m"`
    `echo -e "\033[32m [u].查看系統(tǒng)負載\033[0m"`
    `echo -e "\033[35m [q].退出程序\033[0m"`
EOF
read -p "請輸入要查詢的信息編號: " NUM
if [ "$NUM" = "h" ];then
    sleep 1
    clear
    echo -e "\033[32m\n\t\t\t\t[刷新成功!]\033[0m"
elif [ "$NUM" = "f" ];then
    echo -e "\033[32m\n\t\t\t\t當前在登錄[$user]用戶\033[0m"
    who
elif [ "$NUM" = "d" ];then
    echo -e "\033[32m\n\t\t\t\t[當前磁盤掛載情況!]\033[0m"
    fdisk -l
elif [ "$NUM" = "m" ];then
    echo -e "\033[32m\n\t\t\t\t[當前內(nèi)存已用$free2%]\033[0m"
    free -h
elif [ "$NUM" = "u" ];then
    echo -e "\033[32m\n\t\t\t\t[15分鐘內(nèi)系統(tǒng)負載為$uptime]\033[0m"
    uptime
elif [ "$NUM" = "q" ];then
    echo "bye~客官"
    exit 0
else
    echo -e "\033[31m\n\t\t\t\t輸出格式不對!請重新輸入編號\033[0m"
fi
done

實現(xiàn)效果

[root@shell lianxi]# sh menu.sh 
     [h].顯示命令幫助
     [f].顯示登錄信息
     [d].顯示磁盤掛載
     [m].查看內(nèi)存使用
     [u].查看系統(tǒng)負載
     [q].退出程序
請輸入要查詢的信息編號: h

                [刷新成功!]
     [h].顯示命令幫助
     [f].顯示登錄信息
     [d].顯示磁盤掛載
     [m].查看內(nèi)存使用
     [u].查看系統(tǒng)負載
     [q].退出程序
請輸入要查詢的信息編號: f

                當前在登錄[3]用戶
root     tty1         Jul 18 15:17
root     pts/0        Jul 18 08:34 (10.0.0.1)
root     pts/1        Jul 18 08:49 (10.0.0.1)
     [h].顯示命令幫助
     [f].顯示登錄信息
     [d].顯示磁盤掛載
     [m].查看內(nèi)存使用
     [u].查看系統(tǒng)負載
     [q].退出程序
請輸入要查詢的信息編號: d

                [當前磁盤掛載情況!]

Disk /dev/sda: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000e3d5f

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      411647      204800   83  Linux
/dev/sda2          411648     2508799     1048576   82  Linux swap / Solaris
/dev/sda3         2508800    41943039    19717120   83  Linux
     [h].顯示命令幫助
     [f].顯示登錄信息
     [d].顯示磁盤掛載
     [m].查看內(nèi)存使用
     [u].查看系統(tǒng)負載
     [q].退出程序
請輸入要查詢的信息編號: m

                [當前內(nèi)存已用11%]
              total        used        free      shared  buff/cache   available
Mem:           972M        107M        400M        7.7M        464M        688M
Swap:          1.0G          0B        1.0G
     [h].顯示命令幫助
     [f].顯示登錄信息
     [d].顯示磁盤掛載
     [m].查看內(nèi)存使用
     [u].查看系統(tǒng)負載
     [q].退出程序
請輸入要查詢的信息編號: u

                [15分鐘內(nèi)系統(tǒng)負載為0.05]
 20:14:06 up 11:42,  3 users,  load average: 0.00, 0.01, 0.05
     [h].顯示命令幫助
     [f].顯示登錄信息
     [d].顯示磁盤掛載
     [m].查看內(nèi)存使用
     [u].查看系統(tǒng)負載
     [q].退出程序
請輸入要查詢的信息編號: q
bye~客官
[root@shell lianxi]# 

3盛泡、while循環(huán)批量創(chuàng)建10個用戶,并通過傳參方式傳入密碼123

創(chuàng)建用戶:

useradd test1

添加密碼:

echo 123 | passwd --stdin test1

批量創(chuàng)建

seq 1 10

[root@shell lianxi]# cat user.sh
#!/bin/bash
##############################################################
# File Name: user.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#while循環(huán)批量創(chuàng)建10個用戶娱颊,并通過傳參方式傳入密碼123
i=0
user=0
read -p "請為批量創(chuàng)建的用戶添加密碼: " passwd
#while [ $user -lt 10 ] ;do
while ((i<=10))
do
    ((user=sum+i))
    ((i++))
done
    seq -w $user|sed -r "s#(.*)#useradd test\1;echo $passwd|passwd --stdin test&#g"|bash
[root@shell lianxi]# sh user.sh
請為批量創(chuàng)建的用戶添加密碼: 123A
useradd: user 'test01' already exists
Changing password for user test01.
passwd: all authentication tokens updated successfully.
useradd: user 'test02' already exists
Changing password for user test02.
passwd: all authentication tokens updated successfully.
...
..

[root@shell lianxi]# tail /etc/passwd
test01:x:1002:1002::/home/test01:/bin/bash
test02:x:1003:1003::/home/test02:/bin/bash
test03:x:1004:1004::/home/test03:/bin/bash
test04:x:1005:1005::/home/test04:/bin/bash
test05:x:1006:1006::/home/test05:/bin/bash
test06:x:1007:1007::/home/test06:/bin/bash
test07:x:1008:1008::/home/test07:/bin/bash
test08:x:1009:1009::/home/test08:/bin/bash
test09:x:1010:1010::/home/test09:/bin/bash
test10:x:1011:1011::/home/test10:/bin/bash

4. 用case和while循環(huán)批量刪除用戶[y|n]

#暫時用while加if寫出來了傲诵,此題沒有思路
[root@shell lianxi]# cat userdel.sh 
#!/bin/bash
##############################################################
# File Name: user.sh
# Version: V1.0
# Author: lcx
# Organization: www.oldboyedu.com
##############################################################
#case方法批量刪除用戶
#判斷是否為root用戶
while true ;do
if [ $UID -ne 0 ];then
    echo "必須是root用戶才有刪除的權(quán)限!" user
    exit 1;
fi
read -p "請輸入要刪除的用戶: " name
user=`awk -F: '{print $1}' /etc/passwd|grep "$name"`
if [ $? = 0 ];then
    read -p "此用戶是否真的要刪除[y|n]: " or
    if [ "$or" = "y" ];then
        userdel -r $user
        echo "$user用戶已刪除"
    elif [ "$or" = "n" ];then
        echo "返回主頁..."
    else
        echo "輸入有誤!請重新輸入"
    fi
else
    echo "${name}用戶不存在"
fi
don

5. while循環(huán)通過文本來直接創(chuàng)建用戶和密碼,如果用戶存在或者創(chuàng)建失敗給予提示

shell編程知識點總結(jié)

1.shell是命令解釋器箱硕,可以解釋命令
2.shell腳本是用命令寫成的一個可執(zhí)行的文件
3.shell腳本的用途
批量管理
代碼上線
定時備份拴竹,定時啟停服務(wù)
系統(tǒng)監(jiān)控,服務(wù)監(jiān)控
日志切割剧罩,分析

4.編譯型語言栓拜;
通過某種高級語言翻譯成可被系統(tǒng)識別的二進制碼

5.解釋型語言;
通過解釋器對源程序的二進制碼進行解釋并執(zhí)行

6.centos的默認解釋器是
bash sh

7.父shell的環(huán)境變量惠昔,子shell可以看到
8.子shell的環(huán)境變量幕与,父shell不可以看到
9.shell執(zhí)行的方式
sh &bash
cat *.sh|bash
sh < .sh
/server/scripts/
.sh 可執(zhí)行
source *.sh
. *.sh

10.腳本頂格添加解釋器聲明

!/bin/bash

添加作者 時間 版本號 注釋

11.退出shell的命令是
exit

12.環(huán)境變量也叫全局變量
定義方式;export 變量名=變量值

13.環(huán)境變量的四個執(zhí)行文件順序
/etc/profile--->/.bash_profile--->/.bashrc--->/etc/bashrc
登錄加載所有
非登錄式加載后兩個

14.普通變量只能在當前shell下使用
不加引號:適用于一般場景镇防,不能帶空格 export 變量名=變量值

單引號:所見即所得 export 變量名='變量值'

雙引號:解析雙引號內(nèi)的變量 export 變量名="變量值"

反引號:強制命令解析 export 變量名=命令

變量后有內(nèi)容需要用{} echo ${name}5

15.用source執(zhí)行和用bash執(zhí)行的區(qū)別
source可以越權(quán)的啦鸣,bash不可以越權(quán)(父子shell)
用source或"."執(zhí)行的腳本,變量會在父shell下生效营罢,用bash執(zhí)行的腳本赏陵,變量不會再父shell下生效。

16.參數(shù)特殊變量
0 獲取腳本文件名,如果帶路徑則包括完整路徑n 獲取腳本的第n個參數(shù),如12
# 腳本的參數(shù)個數(shù)* 顯示腳本所有的參數(shù)
$@ 顯示腳本所有的參數(shù)

17.進程特殊變量
? 命令執(zhí)行的狀態(tài)饲漾,0正確 非0錯誤 $$ 腳本當前進程ID號! 后臺運行最后一個進程的ID號
$_ 腳本的最后一個參數(shù)

18.變量子串
{name} 返回變量內(nèi)容{#name} 返回變量字符長度
{name:5}從變量的第五個字符提取子串到結(jié)尾{name:5:3}從變量的第五個字符提取長度為3的子串
{name#abc}刪除變量開頭最短匹配的子串{name##abc}刪除變量開頭最長匹配的子串
{name%abc}刪除變量結(jié)尾最短匹配的子串{name%%abc}刪除變量結(jié)尾最長匹配的子串
{name/abc/ABC}將變量的第一個abc替換為ABC{name//abc/ABC}將變量所有的abc替換為ABC

19.字符串測試表達式
[ "a" = "b" ] 是否相等 賦值不能有空格 判斷時必須有空格
[ "a" != "b" ]是否不相等
[ -n "name" ] 是否非空 [ -z "name" ] 是否為空
[ $name ] 是否非空

20.整數(shù)二元比較操作符
-eq 等于
-ne 不等于
-gt 大于
-ge 大于等于
-lt 小于
-le 小于等于

21.邏輯操作符
-a == && and 與運算 兩端都真則為真
-o == || or 或運算 兩端有一個為真則為真
! != not 非 相反為真

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蝙搔,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子考传,更是在濱河造成了極大的恐慌吃型,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件僚楞,死亡現(xiàn)場離奇詭異勤晚,居然都是意外死亡枉层,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門赐写,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鸟蜡,“玉大人,你說我怎么就攤上這事挺邀∪嗤” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵端铛,是天一觀的道長泣矛。 經(jīng)常有香客問我,道長禾蚕,這世上最難降的妖魔是什么您朽? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮换淆,結(jié)果婚禮上哗总,老公的妹妹穿的比我還像新娘。我一直安慰自己倍试,他們只是感情好魂奥,可當我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著易猫,像睡著了一般。 火紅的嫁衣襯著肌膚如雪具壮。 梳的紋絲不亂的頭發(fā)上准颓,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機與錄音棺妓,去河邊找鬼攘已。 笑死言秸,一個胖子當著我的面吹牛虐拓,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播嗦董,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼性芬,長吁一口氣:“原來是場噩夢啊……” “哼峡眶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起植锉,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤辫樱,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后俊庇,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體狮暑,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡鸡挠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了搬男。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拣展。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖缔逛,靈堂內(nèi)的尸體忽然破棺而出备埃,到底是詐尸還是另有隱情,我是刑警寧澤译株,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布瓜喇,位于F島的核電站,受9級特大地震影響歉糜,放射性物質(zhì)發(fā)生泄漏乘寒。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一匪补、第九天 我趴在偏房一處隱蔽的房頂上張望伞辛。 院中可真熱鬧,春花似錦夯缺、人聲如沸蚤氏。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽竿滨。三九已至,卻和暖如春捏境,著一層夾襖步出監(jiān)牢的瞬間于游,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工垫言, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留筷频,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓凛捏,卻偏偏與公主長得像,于是被迫代替她去往敵國和親涵妥。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,381評論 0 5
  • 本文是對Linux shell編程的一個學(xué)習(xí)比較蓬网,共包括如下章節(jié)的內(nèi)容: 概述 基本語法 結(jié)構(gòu)化語句 函數(shù) 小結(jié) ...
    我是老薛閱讀 830評論 0 5
  • 搭配《linux就該這樣學(xué)》第四章內(nèi)容 1.shell歷史 Shell的作用是解釋執(zhí)行用戶的命令,用戶輸入一條命令...
    木魚_cc閱讀 846評論 0 10
  • 原文地址Shell是用戶與Linux或Unix內(nèi)核通信的工具,shell編程指的并不是編寫這個工具,而是指利用現(xiàn)有...
    MrRobot閱讀 11,845評論 5 30
  • 本文將結(jié)合前面介紹的Linux命令、管道符等知識摄乒,通過VI編輯器編寫Shell腳本残黑,實現(xiàn)能自動化工作的腳本文件梨水。 ...
    黑馬騰云閱讀 313評論 0 1