當前位置:首頁 » 編程軟體 » shell腳本elif

shell腳本elif

發布時間: 2023-01-31 14:13:58

1. shell腳本中的if中多條件語句如何寫。

可以使用 if-elif-else 語法來寫多條件語句。

1、首先要理解if-else的基本用法,if條件+then操作+else操作+fi閉合,書寫方法如下:

2、 shell語法中[[ ]]和[ ]的主要區別

(1) [ ] 實際上是bash 中 test 命令的簡寫。即所有的 [ expr ] 等於 test expr。
對 test 命令來說, 用 -eq 要進行數字比較,而你此時傳入字元串,就報錯了。


(2) [[ ]] 是內置在shell中的一個命令,它比test強大的多。支持字元串的模式匹配(使用=~操作符時甚至支持shell的正則表達式)。邏輯組合可以不使用test的-a,-o而使用&& ||。

2. shell腳本主要有哪些

第一個shell腳本程序:

#!/bin/bash
# 上面中的 #! 是一種約定標記, 它可以告訴系統這個腳本需要什麼樣的解釋器來執行;echo "Hello, world!"

變數:

定義變數:

country="China"Number=100

注意: 1,變數名和等號之間不能有空格;

2,首個字元必須為字母(a-z,A-Z)。

3, 中間不能有空格,可以使用下劃線(_)。

4, 不能使用標點符號。

5, 不能使用bash里的關鍵字(可用help命令查看保留關鍵字)。

使用變數:

只需要在一個定義過的變數前面加上美元符號$就可以了, 另外,對於變數的{} 是可以選擇的, 它的目的為幫助解釋器識別變數的邊界.

country="China"echo $countryecho ${country}echo "I love my ${country}abcd!"

#這個需要有{}的;

重定義變數:直接把變數重新像開始定義的那樣子賦值就可以了:

country="China"country="ribenguizi"

只讀變數: 用 readonly 命令 可以把變數字義為只讀變數。

readonly country="China"#或
country="China"readonly country

刪除變數: 使用unset命令可以刪除變數,但是不能刪除只讀的變數。用法:

unset variable_name

變數類型

運行shell時,會同時存在三種變數:

1) 局部變數

局部變數在腳本或命令中定義,僅在當前shell實例中有效,其他shell啟動的程序不能訪問局部變數。

2) 環境變數

所有的程序,包括shell啟動的程序,都能訪問環境變數,有些程序需要環境變數來保證其正常運行。必要的時候shell腳本也可以定義環境變數。

3) shell變數

shell變數是由shell程序設置的特殊變數。shell變數中有一部分是環境變數,有一部分是局部變數,這些變數保證了shell的正常運行

特殊變數:

其中, 1. 取值後面必須為關鍵字 in,每一模式必須以右括弧結束。取值可以為變數或常數。匹配發現取值符合某一模式後,其間所有命令開始執行直至 ;;。;; 與其他語言中的 break 類似,意思是跳到整個 case 語句的最後。2. 如果無一匹配模式,使用星號 * 捕獲該值,再執行後面的命令。

3. 如何給shell腳本傳參數

方法/步驟

執行「nano test.sh」創建一個新的shell腳本。

腳本test.sh的內容如下:
#!/bin/sh

name=$1

echo "the ${name} are great man!"

給新創建的test.sh的腳本賦可執行許可權,命令為「chmod 755 test.sh」。

執行'./test.sh "xiao wang"'命令,可以看到自己編寫腳本的結果「the xiao wang are great man!」。

"name=$1"中$1為系統提供的位置參數,$0代表程序的名稱,[$1/$2/...]從1開始為傳遞的參數。
linux系統除了提供位置參數還提供內置參數,內置參數如下:
$# ----傳遞給程序的總的參數數目
$? ----上一個代碼或者shell程序在shell中退出的情況,如果正常退出則返回0,反之為非0值。
$* ----傳遞給程序的所有參數組成的字元串。
$n ----表示第幾個參數,$1 表示第一個參數,$2 表示第二個參數 ... $0 ----當前程序的名稱
$@----以"參數1" "參數2" ... 形式保存所有參數
$$ ----本程序的(進程ID號)PID
$! ----上一個命令的PID

4. Shell 腳本 比較數字大小

你的寫下正確的,以下的也行
if [[ $DEV_SIZE -ge ${EXT_LIMIT[0]} && $DEV_SIZE -le ${EXT_LIMIT[1]} ]];
if [ $DEV_SIZE -ge ${EXT_LIMIT[0]} -a $DEV_SIZE -le ${EXT_LIMIT[1]} ];

如果使用[ ]或者[[ ]]進行整數測試的,裡面的比較運算符要使用-eq或-le或-ge等符號,在((裡面才可以用>=和<=比較運算,而且[[ 裡面邏輯運算用&&和||, [ 裡面邏輯運算用-a和-o,((也可以用&&和||

5. 如何使用shell 腳本語法書寫 if 分支語句

和C語言類似,在Shell中也可以實現分支語句。用if、then、elif、else、fi這幾條命令實現分支控制。這種流程式控制制語句本質上也是由若干條Shell命令組成的,例如:
?#! /bin/sh
??
?if [ -f ~/.bashrc ]; then
? . ~/.bashrc

?fi

目前在黑馬程序員學習C/C++,還不會用,然後在社區查了一下,分享給你,如果你有什麼不了解的,也可以去查一下,看一看啊

6. shell腳本上

| 對於初學者而言,因為沒有實戰經驗,寫不出來 Shell 腳本 很正常,如果工作了幾年的運維老年還是寫不出來,那就是沒主動找需求,缺乏練習,缺乏經驗。針對以上問題,總結了30個生產環境中經典的 Shell 腳本 ,通過這些需求案例,希望能幫助大家提升Shell編寫思路,掌握編寫技巧。 |

先了解下編寫Shell過程中注意事項:

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">開頭加解釋器:#!/bin/bash
語法縮進,使用四個空格;多加註釋說明。
命名建議規則:變數名大寫、局部變數小寫,函數名小寫,名字體現出實際作用。
默認變數是全局的,在函數中變數local指定為局部變數,避免污染其他作用域。
有兩個 命令 能幫助我調試腳本:set -e 遇到執行非0時退出腳本,set-x 列印執行過程。
寫腳本一定先測試再到生產上。
</pre>

1、獲取隨機字元串或數字

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">獲取隨機8位字元串:
方法1:

471b94f2
方法2:

vg3BEg==
方法3:

ed9e032c

獲取隨機8位數字:
方法1:

23648321
方法2:

38571131
方法3:

69024815

cksum:列印CRC效驗和統計位元組
</pre>

2、定義一個顏色輸出字元串函數

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">方法1:
function echo_color() {
if [ 233[0m"
elif [ 233[0m"
fi
}
方法2:
function echo_color() {
case 2[0m"
;;
red)
echo -e "[31;40m$2[0m"
;;
*)
echo "Example: echo_color red string"
esac
}

使用方法:echo_color green "test"

function關鍵字定義一個函數,可加或不加。
</pre>

3、批量創建用戶

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
DATE= 1 == "green" ]; then
echo -e "[32;40m 1 == "red" ]; then
echo -e "[31;40m$2[0m"
fi
}

if [ -s USER_FILE {DATE}.bak
echo_color green " {USER_FILE}- USER_FILE
echo "----------------" >> USER &>/dev/null; then
PASS= RANDOM |md5sum |cut -c 1-8)
useradd PASS |passwd --stdin USER USER_FILE
echo " USER User already exists!"
fi
done
</pre>

4、檢查軟體包是否安裝

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
if rpm -q sysstat &>/dev/null; then
echo "sysstat is already installed."
else
echo "sysstat is not installed!"
fi
</pre>

5、檢查服務狀態

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
PORT_C= (ps -ef |grep ntpd |grep -vc grep)
if [ PS_C -eq 0 ]; then
echo "內容" | mail -s "主題" [email protected]
fi
</pre>

6、檢查主機存活狀態

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">方法1:將錯誤IP放到數組裡面判斷是否ping失敗三次

IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in NUM -le 3 ]; do
if ping -c 1 IP Ping is successful."
break
else
# echo " NUM"
FAIL_COUNT[ IP
let NUM++
fi
done
if [ {FAIL_COUNT[1]} Ping is failure!"
unset FAIL_COUNT[*]
fi
done

方法2:將錯誤次數放到FAIL_COUNT變數裡面判斷是否ping失敗三次

IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in IP >/dev/null; then
echo " IP Ping is failure FAIL_COUNT -eq 3 ]; then
echo "$IP Ping is failure!"
fi
done

方法3:利用for循環將ping通就跳出循環繼續,如果不跳出就會走到列印ping失敗

ping_success_status() {
if ping -c 1 IP Ping is successful."
continue
fi
}
IP_LIST="192.168.18.1 192.168.1.1 192.168.18.2"
for IP in IP Ping is failure!"
done
</pre>

7、監控CPU、內存和硬碟利用率

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">1)CPU
藉助vmstat工具來分析CPU統計信息。

DATE= (ifconfig eth0 |awk -F [ :]+ /inet addr/{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print (vmstat |awk NR==3{print (( SY))
if [ DATE
Host: USE
" | mail -s "CPU Monitor" $MAIL
fi

2)內存

DATE= (ifconfig eth0 |awk -F [ :]+ /inet addr/{print (free -m |awk /Mem/{print (free -m |awk /Mem/{print 6- (( USE))

if [ DATE
Host: TOTAL,Use= FREE
" | mail -s "Memory Monitor" $MAIL
fi

3)硬碟

DATE= (ifconfig eth0 |awk -F [ :]+ /inet addr/{print (fdisk -l |awk -F [: ]+ BEGIN{OFS="="}/^Disk /dev/{printf "%s=%sG,", 3} )
PART_USE= 1,int( 6} )
for i in (echo (echo (echo USE -gt 80 ]; then
echo "
Date: IP
Total: PART= MOUNT)
" | mail -s "Disk Monitor" $MAIL
fi
done
</pre>

8、批量主機磁碟利用率監控

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">前提監控端和被監控端SSH免交互登錄或者密鑰登錄。

寫一個配置文件保存被監控主機SSH連接信息,文件內容格式:IP User Port

HOST_INFO=host.info
for IP in 1} (awk -v ip= 1{print HOST_INFO)
PORT= IP ip== 3} PORT IP df -h > (awk BEGIN{OFS="="}/^/dev/{print 5)} USE_RATE_LIST; do
PART_NAME= {USE_RATE#*=}
if [ PART_NAME Partition usage $USE_RATE%!"
fi
done
done
</pre>

9、檢查網站可用性

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">1)檢查URL可用性
方法1:
check_url() {
HTTP_CODE= 1)
if [ 1 Access failure!"
fi
}
方法2:
check_url() {
if ! wget -T 10 --tries=1 --spider $1 >/dev/null 2>&1; then

}

使用方法:check_url www..com

2)判斷三次URL可用性
思路與上面檢查主機存活狀態一樣。

方法1:利用循環技巧,如果成功就跳出當前循環,否則執行到最後一行

check_url() {
HTTP_CODE= 1)
if [ URL_LIST; do
check_url URL
check_url URL Access failure!"
done

方法2:錯誤次數保存到變數

URL_LIST=" www..com www.agasgf.com "
for URL in (curl -o /dev/null --connect-timeout 3 -s -w "%{http_code}" HTTP_CODE -ne 200 ]; then
let FAIL_COUNT++
else
break
fi
done
if [ URL Access failure!"
fi
done

方法3:錯誤次數保存到數組

URL_LIST=" www..com www.agasgf.com "
for URL in NUM -le 3 ]; do
HTTP_CODE= URL)
if [ NUM]= NUM下標, {#FAIL_COUNT[ ]} -eq 3 ]; then
echo "Warning: $URL Access failure!"
unset FAIL_COUNT[ ] #清空數組
fi
done
</pre>

10、檢查MySQL主從同步狀態

<pre style="margin: 0px; padding: 0px; overflow: auto; white-space: pre-wrap; color: rgb(51, 51, 51); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">#!/bin/bash
USER=bak
PASSWD=123456
IO_SQL_STATUS= USER -p 0} ) #gsub去除冒號後面的空格
for i in {i%:*}
THREAD_STATUS= THREAD_STATUS" != "Yes" ]; then
echo "Error: MySQL Master-Slave THREAD_STATUS!"
fi
done
</pre>

動手練一練,讓你的Shell功底上升一個段位!

7. Shell 腳本 if 判斷後,怎麼終止當前腳本但不退出 shell

代碼如下:

if list then
do something here
elif list then
do another thing here
else
do something else here
fi

EX1:

復制代碼代碼如下:

#!/bin/sh
SYSTEM=`uname -s` #獲取操作系統類型,我本地是linux
if [ $SYSTEM = "Linux" ] ; then #如果是linux的話列印linux字元串
echo "Linux"
elif [ $SYSTEM = "FreeBSD" ] ; then
echo "FreeBSD"
elif [ $SYSTEM = "Solaris" ] ; then
echo "Solaris"
else
echo "What?"
fi #ifend

基本上和其他腳本語言一樣。沒有太大區別。不過值得注意的是。[]裡面的條件判斷。

8. 關於如何學習shell腳本,該怎麼寫

1. Linux 腳本編寫基礎
1.1 語法基本介紹
1.1.1 開頭
程序必須以下面的行開始(必須方在文件的第一行):
#!/bin/sh
符號#!用來告訴系統它後面的參數是用來執行該文件的程序。在這個例子中我們使用/bin/sh來執行程序。
當編輯好腳本時,如果要執行該腳本,還必須使其可執行。
要使腳本可執行:
編譯 chmod +x filename 這樣才能用./filename 來運行
1.1.2 注釋
在進行shell編程時,以#開頭的句子表示注釋,直到這一行的結束。我們真誠地建議您在程序中使用注釋。
如果您使用了注釋,那麼即使相當長的時間內沒有使用該腳本,您也能在很短的時間內明白該腳本的作用
及工作原理。
1.1.3 變數
在其他編程語言中您必須使用變數。在shell編程中,所有的變數都由字元串組成,並且您不需要對變數
進行聲明。要賦值給一個變數,您可以這樣寫:
#!/bin/sh
#對變數賦值:
a="hello world"
# 現在列印變數a的內容:
echo "A is:"
echo $a
有時候變數名很容易與其他文字混淆,比如:
num=2
echo "this is the $numnd"
這並不會列印出"this is the 2nd",而僅僅列印"this is the ",因為shell會去搜索變數numnd的值,
但是這個變數時沒有值的。可以使用花括弧來告訴shell我們要列印的是num變數:
num=2
echo "this is the ${num}nd"
這將列印: this is the 2nd
1.1.4 環境變數
由export關鍵字處理過的變數叫做環境變數。我們不對環境變數進行討論,因為通常情況下僅僅在登錄
腳本中使用環境變數。
1.1.5 Shell命令和流程式控制制
在shell腳本中可以使用三類命令:
1)Unix 命令:
雖然在shell腳本中可以使用任意的unix命令,但是還是由一些相對更常用的命令。這些命令通常是用來
進行文件和文字操作的。
常用命令語法及功能
echo "some text": 將文字內容列印在屏幕上
ls: 文件列表
wc –l filewc -w filewc -c file: 計算文件行數計算文件中的單詞數計算文件中的字元數
cp sourcefile destfile: 文件拷貝
mv oldname newname : 重命名文件或移動文件
rm file: 刪除文件
grep 'pattern' file: 在文件內搜索字元串比如:grep 'searchstring' file.txt
cut -b colnum file: 指定欲顯示的文件內容範圍,並將它們輸出到標准輸出設備比如:輸出
每行第5個到第9個字元cut -b5-9 file.txt千萬不要和cat命令混淆,
這是兩個完全不同的命令
cat file.txt: 輸出文件內容到標准輸出設備(屏幕)上
file somefile: 得到文件類型
read var: 提示用戶輸入,並將輸入賦值給變數
sort file.txt: 對file.txt文件中的行進行排序
uniq: 刪除文本文件中出現的行列比如: sort file.txt | uniq
expr: 進行數學運算Example: add 2 and 3expr 2 "+" 3
find: 搜索文件比如:根據文件名搜索find . -name filename -print
tee: 將數據輸出到標准輸出設備(屏幕) 和文件比如:somecommand | tee outfile
basename file: 返回不包含路徑的文件名比如: basename /bin/tux將返回 tux
dirname file: 返迴文件所在路徑比如:dirname /bin/tux將返回 /bin
head file: 列印文本文件開頭幾行
tail file : 列印文本文件末尾幾行
sed: Sed是一個基本的查找替換程序。可以從標准輸入(比如命令管道)讀入文本,並將
結果輸出到標准輸出(屏幕)。該命令採用正則表達式(見參考)進行搜索。
不要和shell中的通配符相混淆。比如:將linuxfocus 替換為
LinuxFocus :cat text.file | sed 's/linuxfocus/LinuxFocus/' > newtext.file
awk: awk 用來從文本文件中提取欄位。預設地,欄位分割符是空格,可以使用-F指定其他分割符。
cat file.txt | awk -F, '{print $1 "," $3 }'這里我們使用,作為欄位分割符,同時列印
第一個和第三個欄位。如果該文件內容如下: Adam Bor, 34, IndiaKerry Miller, 22, USA
命令輸出結果為:Adam Bor, IndiaKerry Miller, USA
2) 概念: 管道, 重定向和 backtick
這些不是系統命令,但是他們真的很重要。
管道 (|) 將一個命令的輸出作為另外一個命令的輸入。
grep "hello" file.txt | wc -l
在file.txt中搜索包含有」hello」的行並計算其行數。
在這里grep命令的輸出作為wc命令的輸入。當然您可以使用多個命令。
重定向:將命令的結果輸出到文件,而不是標准輸出(屏幕)。
> 寫入文件並覆蓋舊文件
>> 加到文件的尾部,保留舊文件內容。
反短斜線
使用反短斜線可以將一個命令的輸出作為另外一個命令的一個命令行參數。
命令:
find . -mtime -1 -type f -print
用來查找過去24小時(-mtime –2則表示過去48小時)內修改過的文件。如果您
想將所有查找到的文件打一個包,則可以使用以下腳本:
#!/bin/sh
# The ticks are backticks (`) not normal quotes ('):
tar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print`
3) 流程式控制制
1.if
"if" 表達式 如果條件為真則執行then後面的部分:
if ....; then
....
elif ....; then
....
else
....
fi
大多數情況下,可以使用測試命令來對條件進行測試。比如可以比較字元串、判斷文件
是否存在及是否可讀等等…
通常用" [ ] "來表示條件測試。注意這里的空格很重要。要確保方括弧的空格。
[ -f "somefile" ] :判斷是否是一個文件
[ -x "/bin/ls" ] :判斷/bin/ls是否存在並有可執行許可權
[ -n "$var" ] :判斷$var變數是否有值
[ "$a" = "$b" ] :判斷$a和$b是否相等
執行man test可以查看所有測試表達式可以比較和判斷的類型。
直接執行以下腳本:
#!/bin/sh
if [ "$SHELL" = "/bin/bash" ]; then
echo "your login shell is the bash (bourne again shell)"
else
echo "your login shell is not bash but $SHELL"
fi
變數$SHELL包含了登錄shell的名稱,我們和/bin/bash進行了比較。
快捷操作符
熟悉C語言的朋友可能會很喜歡下面的表達式:
[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors"
這里 && 就是一個快捷操作符,如果左邊的表達式為真則執行右邊的語句。
您也可以認為是邏輯運算中的與操作。上例中表示如果/etc/shadow文件存在
則列印」 This computer uses shadow passwors」。同樣或操作(||)在shell編程中也是
可用的。這里有個例子:
#!/bin/sh
mailfolder=/var/spool/mail/james
[ -r "$mailfolder" ]' '{ echo "Can not read $mailfolder" ; exit 1; }
echo "$mailfolder has mail from:"
grep "^From " $mailfolder
該腳本首先判斷mailfolder是否可讀。如果可讀則列印該文件中的"From" 一行。如果不可讀
則或操作生效,列印錯誤信息後腳本退出。這里有個問題,那就是我們必須有兩個命令:
-列印錯誤信息
-退出程序
我們使用花括弧以匿名函數的形式將兩個命令放到一起作為一個命令使用。一般函數將在下文提及。
不用與和或操作符,我們也可以用if表達式作任何事情,但是使用與或操作符會更便利很多。
2.case
case :表達式可以用來匹配一個給定的字元串,而不是數字。
case ... in
...) do something here ;;
esac
讓我們看一個例子。 file命令可以辨別出一個給定文件的文件類型,比如:
file lf.gz
這將返回:
lf.gz: gzip compressed data, deflated, original filename,
last modified: Mon Aug 27 23:09:18 2001, os: Unix
我們利用這一點寫了一個叫做smartzip的腳本,該腳本可以自動解壓bzip2, gzip 和zip 類型的壓縮文件:
#!/bin/sh
ftype=`file "$1"`
case "$ftype" in
"$1: Zip archive"*)
unzip "$1" ;;
"$1: gzip compressed"*)
gunzip "$1" ;;
"$1: bzip2 compressed"*)
bunzip2 "$1" ;;
*) echo "File $1 can not be uncompressed with smartzip";;
esac
您可能注意到我們在這里使用了一個特殊的變數$1。該變數包含了傳遞給該程序的第一個參數值。
也就是說,當我們運行:
smartzip articles.zip
$1 就是字元串 articles.zip
3. selsect
select 表達式是一種bash的擴展應用,尤其擅長於互動式使用。用戶可以從一組不同的值中進行選擇。
select var in ... ; do
break
done
.... now $var can be used ....
下面是一個例子:
#!/bin/sh
echo "What is your favourite OS?"
select var in "Linux" "Gnu Hurd" "Free BSD" "Other"; do
break
done
echo "You have selected $var"
下面是該腳本運行的結果:
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux
4.loop
loop表達式:
while ...; do
....
done
while-loop 將運行直到表達式測試為真。will run while the expression that we test for is true.
關鍵字"break" 用來跳出循環。而關鍵字」continue」用來不執行餘下的部分而直接跳到下一個循環。

for-loop表達式查看一個字元串列表 (字元串用空格分隔) 然後將其賦給一個變數:
for var in ....; do
....
done
在下面的例子中,將分別列印ABC到屏幕上:
#!/bin/sh
for var in A B C ; do
echo "var is $var"
done
下面是一個更為有用的腳本showrpm,其功能是列印一些RPM包的統計信息:
#!/bin/sh
# list a content summary of a number of RPM packages
# USAGE: showrpm rpmfile1 rpmfile2 ...
# EXAMPLE: showrpm /cdrom/RedHat/RPMS/*.rpm
for rpmpackage in $*; do
if [ -r "$rpmpackage" ];then
echo "=============== $rpmpackage =============="
rpm -qi -p $rpmpackage
else
echo "ERROR: cannot read file $rpmpackage"
fi
done
這里出現了第二個特殊的變數$*,該變數包含了所有輸入的命令行參數值。
如果您運行showrpm openssh.rpm w3m.rpm webgrep.rpm
此時 $* 包含了 3 個字元串,即openssh.rpm, w3m.rpm and webgrep.rpm.
5. 引號
在向程序傳遞任何參數之前,程序會擴展通配符和變數。這里所謂擴展的意思是程序會把通配符
(比如*)替換成合適的文件名,它變數替換成變數值。為了防 止程序作這種替換,您可以使用
引號:讓我們來看一個例子,假設在當前目錄下有一些文件,兩個jpg文件, mail.jpg 和tux.jpg。
1.2 編譯SHELL腳本
#ch#!/bin/sh mod +x filename
cho *.jpg ∪緩螅 梢醞ü 淙耄?./filename 來執行您的腳本。
這將列印出"mail.jpg tux.jpg"的結果。
引號 (單引號和雙引號) 將防止這種通配符擴展:
#!/bin/sh
echo "*.jpg"
echo '*.jpg'
這將列印"*.jpg" 兩次。
單引號更嚴格一些。它可以防止任何變數擴展。雙引號可以防止通配符擴展但允許變數擴展。
#!/bin/sh
echo $SHELL
echo "$SHELL"
echo '$SHELL'
運行結果為:
/bin/bash
/bin/bash
$SHELL
最後,還有一種防止這種擴展的方法,那就是使用轉義字元——反斜桿:
echo *.jpg
echo $SHELL
這將輸出:
*.jpg
$SHELL
6. Here documents
當要將幾行文字傳遞給一個命令時,here documents(譯者註:目前還沒有見到過對該詞適合的翻譯)
一種不錯的方法。對每個腳本寫一段幫助性的文字是很有用的,此時如果我們四有那個 here documents
就不必用echo函數一行行輸出。 一個 "Here document" 以 shift by 2
--) shift;break;; # end of options
-*) echo "error: no such option $1. -h for help";exit 1;;
*) break;;
esac
done
echo "opt_f is $opt_f"
echo "opt_l is $opt_l"
echo "first arg is $1"
echo "2nd arg is $2"
您可以這樣運行該腳本:
cmdparser -l hello -f -- -somefile1 somefile2
返回的結果是:
opt_f is 1
opt_l is hello
first arg is -somefile1
2nd arg is somefile2
這個腳本是如何工作的呢?腳本首先在所有輸入命令行參數中進行循環,將輸入參數
與case表達式進行比較,如果匹配則設置一個變數並且移除該參數。根據unix系統的慣例,
首先輸入的應該是包含減號的參數.
第2部分 實例
現在我們來討論編寫一個腳本的一般步驟。任何優秀的腳本都應該具有幫助和輸入參數。並且寫一個偽腳本(framework.sh),該腳本包含了大多數腳本都需要的框架結構,是一個非常不錯的主意。這時候,在寫一個新的腳本時我們只需要執行一下命令:
cp framework.sh myscript
然後再插入自己的函數。
讓我們再看兩個例子:
二進制到十進制的轉換
腳本 b2d 將二進制數 (比如 1101) 轉換為相應的十進制數。這也是一個用expr命令進行數學運算的例子:
#!/bin/sh
# vim: set sw=4 ts=4 et:
help()
{
cat <
b2h -- convert binary to decimal
USAGE: b2h [-h] binarynum
OPTIONS: -h help text
EXAMPLE: b2h 111010
will return 58
HELP
exit 0
}
error()
{
# print an error and exit
echo "$1"
exit 1
}
lastchar()
{
# return the last character of a string in $rval
if [ -z "$1" ]; then
# empty string
rval=""
return
fi
# wc puts some space behind the output this is why we need sed:
numofchar=`echo -n "$1" | wc -c | sed 's/ //g' `
# now cut out the last char
rval=`echo -n "$1" | cut -b $numofchar`
}
chop()
{
# remove the last character in string and return it in $rval
if [ -z "$1" ]; then
# empty string
rval=""
return
fi
# wc puts some space behind the output this is why we need sed:
numofchar=`echo -n "$1" | wc -c | sed 's/ //g' `
if [ "$numofchar" = "1" ]; then
# only one char in string
rval=""
return
fi
numofcharminus1=`expr $numofchar "-" 1`
# now cut all but the last char:
rval=`echo -n "$1" | cut -b 0-${numofcharminus1}`
}
while [ -n "$1" ]; do
case $1 in
-h) help;shift 1;; # function help is called
--) shift;break;; # end of options
-*) error "error: no such option $1. -h for help";;
*) break;;
esac
done
# The main program
sum=0
weight=1
# one arg must be given:
[ -z "$1" ] && help
binnum="$1"
binnumorig="$1"
while [ -n "$binnum" ]; do
lastchar "$binnum"
if [ "$rval" = "1" ]; then
sum=`expr "$weight" "+" "$sum"`
fi
# remove the last position in $binnum
chop "$binnum"
binnum="$rval"
weight=`expr "$weight" "*" 2`
done
echo "binary $binnumorig is decimal $sum"
該腳本使用的演算法是利用十進制和二進制數權值 (1,2,4,8,16,..),比如二進制"10"可以這樣轉換成十進制:
0 * 1 + 1 * 2 = 2
為了得到單個的二進制數我們是用了lastchar 函數。該函數使用wc –c計算字元個數,然後使用cut命令取出末尾一個字元。Chop函數的功能則是移除最後一個字元。
文件循環程序
或許您是想將所有發出的郵件保存到一個文件中的人們中的一員,但是在過了幾個月
以後,這個文件可能會變得很大以至於使對該文件的訪問速度變慢。下面的 腳本rotatefile
可以解決這個問題。這個腳本可以重命名郵件保存文件(假設為outmail)為outmail.1,
而對於outmail.1就變成了outmail.2 等等等等...

熱點內容
java返回this 發布:2025-10-20 08:28:16 瀏覽:750
製作腳本網站 發布:2025-10-20 08:17:34 瀏覽:1012
python中的init方法 發布:2025-10-20 08:17:33 瀏覽:719
圖案密碼什麼意思 發布:2025-10-20 08:16:56 瀏覽:879
怎麼清理微信視頻緩存 發布:2025-10-20 08:12:37 瀏覽:774
c語言編譯器怎麼看執行過程 發布:2025-10-20 08:00:32 瀏覽:1127
郵箱如何填寫發信伺服器 發布:2025-10-20 07:45:27 瀏覽:351
shell腳本入門案例 發布:2025-10-20 07:44:45 瀏覽:229
怎麼上傳照片瀏覽上傳 發布:2025-10-20 07:44:03 瀏覽:912
python股票數據獲取 發布:2025-10-20 07:39:44 瀏覽:876