標籤:變數 環境變數 位置變數 預定義變數 條件測試
一、變數
環境變數、位置變數、預定義變數
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編程之---變數、比較、測試的使用總結