Shell編程之---變數、比較、測試的使用總結

來源:互聯網
上載者:User

標籤:變數   環境變數   位置變數   預定義變數   條件測試   

一、變數

環境變數、位置變數、預定義變數


1、環境變數
env   #查看環境變數

2、位置變數
vi location.sh
#!/bin/bash
 SUM=`expr $1 + $2`
 echo "$1 + $2 = $SUM"
./location 12 34   #則12為第一個位置變了$1,32為第二個位置變了$2。location為預定義變數

3、預定義變數
$#   #表示命令列中位置參數的個數
$*   #表示所有位置參數的內容
$?   #表示執行後的返回狀態,0為正常
$0   #表示當前執行的指令碼或程式名稱

vi yu.sh
#!/bin/bash
name=bak-`date +%y%m%d`.tar.gz
tar zcf $name $* & >/dev/null
echo "execute $0 script"  
echo "complete $#  object"
echo "content is $*"

=========================================================================================


二、條件測試操作[]
1、檔案測試
-d   #判斷是否為directory         [ -d /etc ] && echo "This is a directory"
-e #判斷是否exist          [ -e /var/log/messages ] && echo "exist"
-f   #判斷是否為file          [ -f /etc/passwd ] && echo "This is a file"
-r   #判斷是否有read              [ -r read ] && echo "premission is a read " 
-w   #判斷是否有write        [ -w write ] && echo "premission is a write"
-x   #判斷是否有execute      [ -x execute ] && echp "premission is a execute"
-l   #判斷是否為link
-b   #判斷是否為black       [ -b /dev/sr0 ] && echo "This is a block"
-c   #判斷是否為chatset      [ -c /dev/vcsa ] && echo "This is a charset"

2、整數值比較
-eq   #1等於2
-ne   #1不等於2
-gt   #1大於2
-lt     #1小於2
-ge   #1大於或等於2
-le   #1小於或等於2
user=`who | wc -l`   #$user為3
[ $user -lt 4 ] && echo yes

3、字串比較
=   #第一個字串等於第二個字串
!=   #第一個字串不等於第二個字串
-z    #檢查字串是否為空白,對於未定義或賦予空值的變數視為空白串
[ $LANG = en_US.UTF-8 ] && echo yes

4、邏輯測試
&&   #"而且",當前面和後面兩個條件都成立時,整個測試命令的返回值才為0
||        #"邏輯或",只要前面和後面兩個條件中有一個成立時,整個測試命令的返回值即為0
!   #"邏輯否",只有當指定的條件不成立時,整個測試命令的返回值才為0

[ $LANG != zh_CN.UTF-8 ] && [ $user != 100 ] && echo yes    ##$user=3
[ $LANG != zh_CN.UTF-8 ] || [ $user != 3 ] && echo yes

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.