#!/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!"