Shell編程入門,shell編程
Shell編程入門
一,變數賦值及算術運算
// 範例程式碼:
a=1echo $alet b=$a+1echo $bc=$[a+b]echo $cd=$[c*2]echo $dlet e=d*2echo $ef=$[e%5]echo $f
// 注意“=”號兩邊不能有空格
// 以上程式碼片段將輸出:
1
2
3
6
12
2
二,數組
1,賦值
// 範例程式碼
declare -a arr1=(1 2 3 4)echo ${arr1[0]}arr2=("China" "Japan" "Korea")echo ${arr2[0]}arr3[0]=100echo ${arr3[0]}
// 以上程式碼片段將輸出:
1
China
100
2,遍曆數組
// 範例程式碼
arr2=("China" "Japan" "Korea")for v in ${arr2[@]};do echo ${v}done
// 以上程式碼片段將輸出:
China
Japan
Korea
// 註:${arr2[@]}中的@符號表示元素列表
三,條件判斷
1,整數比較
-lt,小於
-le,小於等於
-eq,等於
-ge,大於等於
-gt,大於
-ne,不等於
// 範例程式碼:
a=1b=2if [ $a -lt $b ];then echo "a<b is true"else echo "a<b is false"fic=3if [ $a -lt $b ] && [ $c -gt $b ];then echo "a<b && c>b is true"else echo "a<b && c>b is false"fi
// 以上程式碼片段將輸出:
a<b is true
a<b && c>b is true
2,字串比較
s1 = s2
s1 != s2
s1 > s2
s1 < s2
-n s1,s1不為null,長度大於零
-z s1,s1為null,長度為零
// 範例程式碼:
s1="China"s2="China"if [ $s1=$s2 ];then echo "s1=s2 is true"else echo "s1=s2 is false"fi
// 以上程式碼片段將輸出:
s1=s2 is true
3,檔案屬性判斷
-a file1 :file1 存在
-d file1 :file1存在並是一個目錄
-e file1 :file1 存在,同-a
-f file1 :file1 存在並且是一個常規的檔案(不是目錄或者其他特殊類型檔案)
-r file1 :有讀的許可權
-s file1 :檔案存在且不為空白
-w file1 :有寫的許可權
-x file1 :有執行的許可權,或者對於目錄有search的許可權
-N file1 :在上次讀取後,檔案有改動
-O file1 :own所屬的檔案
-G file1 :group所屬的檔案
file1 -nt file2 :file1 比 file2 更新,以最後更新時間為準
file1 -ot file2 :file1 比 file2 更舊 ,以最後更新時間為準
// 範例程式碼:
if [ -d "/home" ];then echo "/home dir exists"else echo "/home dir not exists"fi
// 以上程式碼片段將輸出:
s1=s2 is true
/home dir is exists
四,函數定義
函數參數示意:
$0:表示函數名稱
$1:第1個參數
$2:第2個參數
// 範例程式碼:
a=1function func1() { local b=2 return $[a+b+$1]}func1 3b=$?echo $b;
// 以上程式碼片段將輸出:
6
注意:
Shell語言函數返回值不同於傳統語言,Shell中的返回值通常是指命令執行後的返回值,成功0,失敗1;
以上範例程式碼中有return語句,說明函數自訂了返回值,所以可以用 $? 查看這個返回值。
a為全域變數,b為局部變數。
shell編程基礎
#!/bin/sh #俺是命令直譯器sh
# vim: set sw=4 ts=4 et: #這句是注釋,沒神馬用。
help() #我是函數help. {裡放的內容其實就是一個使用資訊,就相當於}
{ # {command --help 之類的描述資訊。}
cat << HELP # {基本上使用方法就是xtitlebar -h or 為空白 才會顯示help資訊}
xtitlebar -- change the name of an xterm, gnome-terminal or kde konsole
USAGE: xtitlebar [-h] "string_for_titelbar"
OPTIONS: -h help text
EXAMPLE: xtitlebar "cvs"
HELP
exit 0
}
# in case of error or if -h is given we call the function help:
[ -z "$1" ] && help #判斷指令碼參數如果為空白 執行help函數
[ "$1" = "-h" ] && help #判斷參數如果為-h 執行help函數
# send the escape sequence to change the xterm titelbar:
echo -e "\033]0;$1\007" # 顯示$1 -e 參數是為了使用後邊\033]0 的ASCII顏色碼。
#
我煩同事怎辦?難道得辭職?
我也有這種感覺,把它想象成一隻討厭的動物就好了。僅僅在那汪汪亂叫