#!/bin/bashecho "\$*=" $*echo "\"\$*\"=""$*"echo "\$@=" $@echo "\"\$@\"=""$@"echo "print each param from \$*"for var in $*do echo "$var"doneecho "print each param from \$@"for var in $@do echo "$var"doneecho "print each param from \"\$*\""for var in"$*"do echo "$var"doneecho "print each param from \"\$@\""for var in"$@"do echo "$var"done
執行 ./test.sh "a" "b" "c" "d",看到下面的結果:
$*= a b c d"$*"= a b c d$@= a b c d"$@"= a b c dprint each param from $*abcdprint each param from $@abcdprint each param from "$*"a b c dprint each param from "$@"abcd
3.3退出狀態
$? 能夠獲取上一個命令的退出狀態。所謂退出狀態,就是上一個命令執行後的返回結果。
退出狀態是一個數字,通常狀況下,大部分命令執行成功會返回 0,失敗返回 1。
不過,也有一些命令返回其餘值,表示不一樣類型的錯誤。
下面例子中,命令成功執行:
$./test.sh ZaraAliFileName:./test.shFirstParameter:ZaraSecondParameter:AliQuotedValues:ZaraAliQuotedValues:ZaraAliTotalNumber of Parameters:2$echo $?0$
#!/bin/bashDATE=`date`echo "Date is $DATE"USERS=`who | wc -l`echo "Logged in user are $USERS"UP=`date ; uptime`echo "Uptime is $UP"
運行結果:
Date is ThuJul203:59:57 MST 2009Loggedin user are 1Uptime is ThuJul203:59:57 MST 200903:59:57 up 20 days,14:03,1 user, load avg:0.13,0.07,0.15
4.2變量替換
變量替換能夠根據變量的狀態(是否爲空、是否認義等)來改變它的值
可使用的變量替換形式:
形式
說明
${var}
變量原本的值
${var:-word}
若是變量 var 爲空或已被刪除(unset),那麼返回 word,但不改變 var 的值。
${var:=word}
若是變量 var 爲空或已被刪除(unset),那麼返回 word,並將 var 的值設置爲 word。
${var:?message}
若是變量 var 爲空或已被刪除(unset),那麼將消息 message 送到標準錯誤輸出,能夠用來檢測變量 var 是否能夠被正常賦值。 若此替換出如今Shell腳本中,那麼腳本將中止運行。
${var:+word}
若是變量 var 被定義,那麼返回 word,但不改變 var 的值。
請看下面的例子:
#!/bin/bashecho ${var:-"Variable is not set"}echo "1 - Value of var is ${var}"echo ${var:="Variable is not set"}echo "2 - Value of var is ${var}"unset varecho ${var:+"This is default value"}echo "3 - Value of var is $var"var="Prefix"echo ${var:+"This is default value"}echo "4 - Value of var is $var"echo ${var:?"Print this message"}echo "5 - Value of var is ${var}"
運行結果:
Variable is not set1-Value of var isVariable is not set2-Value of var is Variable is not set3-Value of var isThis is default value4-Value of var is PrefixPrefix5-Value of var is Prefix
#!/bin/sha=10b=20val=`expr $a + $b`echo "a + b : $val"val=`expr $a - $b`echo "a - b : $val"val=`expr $a \* $b`echo "a * b : $val"val=`expr $b / $a`echo "b / a : $val"val=`expr $b % $a`echo "b % a : $val"if[ $a == $b ]then echo "a is equal to b"fiif[ $a != $b ]then echo "a is not equal to b"fi
運行結果:
a + b :30a - b :-10a * b :200b / a :2b % a :0a is not equal to b
#!/bin/sha=10b=20if[ $a -eq $b ]then echo "$a -eq $b : a is equal to b"else echo "$a -eq $b: a is not equal to b"fiif[ $a -ne $b ]then echo "$a -ne $b: a is not equal to b"else echo "$a -ne $b : a is equal to b"fiif[ $a -gt $b ]then echo "$a -gt $b: a is greater than b"else echo "$a -gt $b: a is not greater than b"fiif[ $a -lt $b ]then echo "$a -lt $b: a is less than b"else echo "$a -lt $b: a is not less than b"fiif[ $a -ge $b ]then echo "$a -ge $b: a is greater or equal to b"else echo "$a -ge $b: a is not greater or equal to b"fiif[ $a -le $b ]then echo "$a -le $b: a is less or equal to b"else echo "$a -le $b: a is not less or equal to b"fi
運行結果:
10-eq 20: a is not equal to b10-ne 20: a is not equal to b10-gt 20: a is not greater than b10-lt 20: a is less than b10-ge 20: a is not greater or equal to b10-le 20: a is less or equal to b
10!=20: a is not equal to b10-lt 100-a 20-gt 15: returns true10-lt 100-o 20-gt 100: returns true10-lt 5-o 20-gt 100: returns false
布爾運算符列表
運算符
說明
舉例
!
非運算,表達式爲 true 則返回 false,不然返回 true。
[ ! false ] 返回 true。
-o
或運算,有一個表達式爲 true 則返回 true。
[ $a -lt 20 -o $b -gt 100 ] 返回 true。
-a
與運算,兩個表達式都爲 true 才返回 true。
[ $a -lt 20 -a $b -gt 100 ] 返回 false。
5.4字符串運算符
先來看一個例子:
#!/bin/sha="abc"b="efg"if[ $a = $b ]then echo "$a = $b : a is equal to b"else echo "$a = $b: a is not equal to b"fiif[ $a != $b ]then echo "$a != $b : a is not equal to b"else echo "$a != $b: a is equal to b"fiif[-z $a ]then echo "-z $a : string length is zero"else echo "-z $a : string length is not zero"fiif[-n $a ]then echo "-n $a : string length is not zero"else echo "-n $a : string length is zero"fiif[ $a ]then echo "$a : string is not empty"else echo "$a : string is empty"fi
運行結果:
abc = efg: a is not equal to babc != efg : a is not equal to b-z abc : string length is not zero-n abc : string length is not zeroabc : string is not empty
#!/bin/shfile="/var/www/tutorialspoint/unix/test.sh"if[-r $file ]then echo "File has read access"else echo "File does not have read access"fiif[-w $file ]then echo "File has write permission"else echo "File does not have write permission"fiif[-x $file ]then echo "File has execute permission"else echo "File does not have execute permission"fiif[-f $file ]then echo "File is an ordinary file"else echo "This is sepcial file"fiif[-d $file ]then echo "File is a directory"else echo "This is not a directory"fiif[-s $file ]then echo "File size is zero"else echo "File size is not zero"fiif[-e $file ]then echo "File exists"else echo "File does not exist"fi
運行結果:
File has read accessFile has write permissionFile has execute permissionFile is an ordinary fileThis is not a directoryFile size is zeroFile exists
# format-string爲雙引號$ printf "%d %s\n"1"abc"1 abc# 單引號與雙引號效果同樣 $ printf '%d %s\n'1"abc"1 abc# 沒有引號也能夠輸出$ printf %s abcdefabcdef# 格式只指定了一個參數,但多出的參數仍然會按照該格式輸出,format-string 被重用$ printf %s abc defabcdef$ printf "%s\n" abc defabcdef$ printf "%s %s %s\n" a b c d e f g h i ja b cd e fg h ij# 若是沒有 arguments,那麼 %s 用NULL代替,%d 用 0 代替$ printf "%s and %d \n"and 0# 若是以 %d 的格式來顯示字符串,那麼會有警告,提示無效的數字,此時默認置爲 0$ printf "The first program always prints'%s,%d\n'"HelloShell-bash: printf:Shell: invalid numberThe first program always prints 'Hello,0'$
#!/bin/sha=10b=20if[ $a == $b ]then echo "a is equal to b"fiif[ $a != $b ]then echo "a is not equal to b"fi
運行結果:
a is not equal to b
2) if ... else ... fi 語句
if ... else ... fi 語句的語法:
if[ expression ]thenStatement(s) to be executed if expression is trueelseStatement(s) to be executed if expression is not truefi
若是 expression 返回 true,那麼 then 後邊的語句將會被執行;不然,執行 else 後邊的語句。
舉個例子:
#!/bin/sha=10b=20if[ $a == $b ]then echo "a is equal to b"else echo "a is not equal to b"fi
執行結果:
a is not equal to b
3) if ... elif ... fi 語句
if ... elif ... fi 語句能夠對多個條件進行判斷,語法爲:
if[ expression 1]thenStatement(s) to be executed if expression 1 is trueelif[ expression 2]thenStatement(s) to be executed if expression 2 is trueelif[ expression 3]thenStatement(s) to be executed if expression 3 is trueelseStatement(s) to be executed if no expression is truefi
#!/bin/sha=10b=20if[ $a == $b ]then echo "a is equal to b"elif[ $a -gt $b ]then echo "a is greater than b"elif[ $a -lt $b ]then echo "a is less than b"else echo "None of the condition met"fi
運行結果:
a is less than b
if ... else 語句也能夠寫成一行,以命令的方式來運行,像這樣:
if test $[2*3]-eq $[1+5];then echo 'The two numbers are equal!';fi;
if ... else 語句也常常與 test 命令結合使用,以下所示:
num1=$[2*3]num2=$[1+5]if test $[num1]-eq $[num2]then echo 'The two numbers are equal!'else echo 'The two numbers are not equal!'fi
輸出:
The two numbers are equal!
test 命令用於檢查某個條件是否成立,與方括號([ ])相似
12.Shell case esac語句
case ... esac 與其餘語言中的 switch ... case 語句相似,是一種多分枝選擇結構。
echo 'Input a number between 1 to 4'echo 'Your number is:\c'read aNumcase $aNum in1) echo 'You select 1';;2) echo 'You select 2';;3) echo 'You select 3';;4) echo 'You select 4';;*) echo 'You do not select a number between 1 to 4';;esac
輸入不一樣的內容,會有不一樣的結果,例如:
Input a number between 1 to 4Your number is:3You select 3
再舉一個例子:
#!/bin/bashoption="${1}"case ${option}in-f) FILE="${2}" echo "File name is $FILE";;-d) DIR="${2}" echo "Dir name is $DIR";;*) echo "`basename ${0}`:usage: [-f file] | [-d directory]" exit 1# Command to come out of the program with status 1;;esac
運行結果:
$./test.shtest.sh: usage:[-f filename ]|[-d directory ]$ ./test.sh -f index.htm$ vi test.sh$ ./test.sh -f index.htmFile name is index.htm$ ./test.sh -d unixDir name is unix$
#!/bin/bashwhile:do echo -n "Input a number between 1 to 5: " read aNumcase $aNum in1|2|3|4|5) echo "Your number is $aNum!";;*) echo "You do not select a number between 1 to 5, game is over!"break;;esacdone
#!/bin/bashwhile:do echo -n "Input a number between 1 to 5: " read aNumcase $aNum in1|2|3|4|5) echo "Your number is $aNum!";;*) echo "You do not select a number between 1 to 5!"continue echo "Game is over!";;esacdone
運行代碼發現,當輸入大於5的數字時,該例中的循環不會結束,語句
echo "Game is over!"
永遠不會被執行。
一樣,continue 後面也能夠跟一個數字,表示跳出第幾層循環。
再看一個 continue 的例子:
#!/bin/bashNUMS="1 2 3 4 5 6 7"for NUM in $NUMSdo Q=`expr $NUM % 2`if[ $Q -eq 0]then echo "Number is an even number!!"continuefi echo "Found odd number"done
運行結果:
Found odd numberNumber is an even number!!Found odd numberNumber is an even number!!Found odd numberNumber is an even number!!Found odd number
#!/bin/bash# Define your function hereHello(){ echo "Url is http://see.xidian.edu.cn/cpp/shell/"}# Invoke your functionHello
運行結果:
$./test.shHelloWorld$
調用函數只須要給出函數名,不須要加括號。
再來看一個帶有return語句的函數:
#!/bin/bashfunWithReturn(){ echo "The function is to get the sum of two numbers..." echo -n "Input first number: " read aNum echo -n "Input another number: " read anotherNum echo "The two numbers are $aNum and $anotherNum !"return $(($aNum+$anotherNum))}funWithReturn# Capture value returnd by last commandret=$?echo "The sum of two numbers is $ret !"
運行結果:
Thefunction is to get the sum of two numbers...Input first number:25Input another number:50The two numbers are 25 and 50!The sum of two numbers is 75!
函數返回值在調用該函數後經過 $? 來得到。
再來看一個函數嵌套的例子:
#!/bin/bash# Calling one function from anothernumber_one (){ echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/" number_two}number_two (){ echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"}number_one
運行結果:
Url_1 is http://see.xidian.edu.cn/cpp/shell/Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/
#!/bin/bashfunWithParam(){ echo "The value of the first parameter is $1 !" echo "The value of the second parameter is $2 !" echo "The value of the tenth parameter is $10 !" echo "The value of the tenth parameter is ${10} !" echo "The value of the eleventh parameter is ${11} !" echo "The amount of the parameters is $# !"# 參數個數 echo "The string of the parameters is $* !"# 傳遞給函數的全部參數}funWithParam 1234567893473
運行腳本:
The value of the first parameter is 1!The value of the second parameter is 2!The value of the tenth parameter is 10!The value of the tenth parameter is 34!The value of the eleventh parameter is 73!The amount of the parameters is 12!The string of the parameters is 1234567893473!"