shell基础2(二)

2015-07-24 06:56:10 · 作者: · 浏览: 9
01 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export PATH read -p "input one of ont, two, three:" valu case $valu in "one") echo "first" ;; "two") echo "second" ;; "three") echo "third" ;; *) echo "error" ;; esac

函数声明必须在shell的最前面
function funName{
}


#!/bin/bash # program:test example 01 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export PATH function prifxit(){ echo -n "you choice is: " } read -p "input one of ont, two, three:" valu case $valu in "one") prifxit; echo "first" ;; "two") prifxit; echo "second" ;; "three") prifxit; echo "third" ;; *) prifxit; echo "error" | tr 'a-z' 'A-Z' #特别注意大小写的转换 ;; esac 
特别注意:sh sh17.sh不能运行,提示错误。这时候修改文件为可执行,就没有错误了。(虽然不知道为什么) cp操作会复制文件的权限 fuhui@ubuntu:~/script$ chmod +x sh17.sh fuhui@ubuntu:~/script$ ./sh17.sh input one of ont, two, three:one you choice is: first fuhui@ubuntu:~/script$ ./sh17.sh input one of ont, two, three:ss you choice is: ERROR 

#!/bin/bash # program:test example 01 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export PATH function prifxit(){ echo -n "the function name $0 : $1" } read -p "input one of ont, two, three:" valu case $valu in "one") prifxit "fuhui"; echo "first" ;; "two") prifxit "hui"; echo "second" ;; "three") prifxit "do"; echo "third" ;; *) prifxit "it"; echo "error" | tr 'a-z' 'A-Z' ;; esac 函数的例子,函数内的$0并没有指明这个函数的名字,而是执行脚本的名称。 注意:函数的$1代表函数的第一个参数,依次类推 fuhui@ubuntu:~/script$ ./sh18.sh input one of ont, two, three: the function name ./sh18.sh : itERROR fuhui@ubuntu:~/script$ ./sh18.sh input one of ont, two, three:one the function name ./sh18.sh : fuhuifirst 

 while [ condition ] <==中括号内为判断式 do <==do 循环的开始! 程序段落 done <==done 循环的结束 until [ condition ] do 程序段落 done 两个循环中值得条件不一样,正好相反。

#!/bin/bash # program:test example 01 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export PATH while [ "$yn" != "yes" -a "$yn" != "YES" ] #特别注意-a是&&的意思,-o是||的意思 ,支持 != do read -p "please input a option :" yn done echo "you option is right"

until的用法,注意准换大小写的用法


V=hello V=`echo $V | tr '[:lower:]' '[:upper:]'` echo $V 下面的转化效果是一样的 echo as | tr '[:lower:]' '[:upper:]' echo as | tr [:lower:] [:upper:] 

 #!/bin/bash # program:test example 01 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export PATH until [ "$yn" = "YES" ] do read -p "please input a option :" yn yn=$(echo $yn | tr 'a-z' 'A-Z') if [ "$yn" = "EXIT" ]; then echo "exit program" break; fi done 

计算1+2+。。。+100 declare -i num=0 done #!/bin/bash # program:test example 01 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin export PATH declare -i sum=0 declare -i num=0 while [ $num -le 100 ] #特别注意 -le 平时使用的时候都是 test $num -le 100 do sum=$(($sum+$num)) #需要注意$sum 和sum的区别 num=$(($num+1)) done echo "the sum is: $sum" exit 0 ~ echo "you option is right"