Shell編程入門

來源:互聯網
上載者:User

標籤:style   blog   io   ar   for   sp   檔案   on   2014   

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編程入門

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.