2015 01 28 Shell學習筆記 條件分支

2021-06-28 11:49:42 字數 2275 閱讀 5586

條件測試舉例

[ -f "$file" ] && echo 1||echo 2

[ -f "file1" -a -e "file2" ] && echo 1||echo 0    (兩個存在為1)

[ -f "file1" -o -e "file2" ] && echo 1||echo 0    (乙個存在為1)

[ -f "file1" ] || [ -e "file2" ]

[ 3 -ne 3 ] ||

[ 3 -ne 3 ] || 放在同一行需要用分號隔開

#條件不成立,後面執行多個命令在大括號裡面{}

[ 3 -ne 3 ] || (echo "i am oldboy !";    echo "i am coming !";    exit 1; )

#小括號也行,最常用的是大括號

字串:[ -n "file" ] && echo 1||echo 0     0     (not zero)

[ -z "file" ] && echo 1||echo 0     1     (zero)           字串比較要加雙引號

[ "file" = "file1" ]        = 號左右需要空格

[ "$" = "$" ] 判斷字串長度

判斷檔案在不在,目錄在不在,並生成相應的目標檔案

sh -x test.sh 檢視除錯過程

判斷記憶體大小,低於100m就進行郵件報警

free -m 實際剩餘記憶體:buffers/cache

free -m|awk '/buffer\// '

vim judge_system.sh

cur_memory=`free -m|awk '/buffer\// '`

chars="current memory is $cur_memory."

if[ "$cur_memory" -lt 100 ]

then

echo $chars

echo $chars|mail -s "$chars" (郵件主題) [email protected]

fi每分鐘檢查:crontab -e (到結尾)新增注釋

#judge_system

* * * * * /bin/sh judge_system.sh(需要路徑) >&/dev/null

shell雙分支if條件語句

單分支:

if 條件

then

指令集fi

雙分支:

if 條件

then

指令集else

指令集fi

特殊寫法:if [ -f "$file" ];then echo 1;else echo 0;fi 相當於:[ -f "$file1" ]&& echo 1||echo 0

多分支結構

if 條件

then

指令elif 條件

then

指令else

指令 fi

判斷數的大小:

#/bin/sh

read -p "pls input two numbers:"a b

if [ a -gt b ]

then

echo "yes,$a > $b"

elif [ a -lt b ]

then

echo "yes,$a < $b"

else

echo "yes,$a = $b"

fi#/bin/sh

a=$1

b=$2

if [ $# -ne 2 ]

then

echo "usage:sh $0 num1 num2"

exit 1 fi

if [ $a -gt $b ]

then

echo "yes,$a > $b"

elif [ $a -lt $b ]

then

echo "yes,$a < $b"

else

echo "yes,$a = $b"

fi(傳參並且對引數進行判斷)

判斷字串是否為數字:(依據把數字去掉看剩下的長度是不是0)

[ -n "`echo $num|sed 's/[0-9]//g'`" -a -n "`echo $num2|sed 's/[0-9]//g'`" ] && echo \

"兩個引數都必須為數字"&& exit 1

shell學習之 shell呼叫shell

2008 05 06 14 43 18 分類 linux 標籤 字型大小 大中小訂閱 fork是最普通的,就是直接在指令碼裡面用 directory script.sh來呼叫script.sh這個指令碼.執行的時候開乙個sub shell執行呼叫的指令碼,sub shell執行的時候,parent ...

學習shell 與shell指令碼 學習筆記

一般模式 編輯模式 命令列命令模式 一般模式下輸入 都會進入命令列模式 我們寫vi命令中最常用的方法 一般模式 0 移動到這一行的最前面字元處 移動到這一行的最後面字元處g 移動到這個檔案的最後一行 gg移動到這個檔案的第一行 n n為數字 游標向下移動n行 word 從游標位置開始向下搜尋乙個名為...

Shell學習之shell語法

shell指令碼就是將完成乙個任務的所有的命令按照執行的先後順序,自上而下寫入到乙個文字檔案中,然後給予執行許可權。shell指令碼的命名 名字要有意義 不超過30個位元組 sh結尾 名字不要太長 區分大小寫 shell指令碼格式 shell指令碼開頭必須指定指令碼執行環境 以 這個特殊符號組合來組...