[root@cnsz142728 scripts]# vim checkfileexist.sh #!/bin/bash FILE=/etc/notexistfile function checkfileexist() { if [ -f $FILE ];then return 0 else return 1 fi } echo "This test will let you know whether $FILE is exists. " checkfileexist if [ $? -eq 0 ];then echo "$FILE exist" else echo "$FILE is not exist" fi "checkfileexist.sh" 17L, 302C written [root@cnsz142728 scripts]# ./checkfileexist.sh This test will let you know whether /etc/notexistfile is exists. /etc/notexistfile is not exist
该脚本中的调用函数是checkfileexist(),以后输入checkfileexist就是调用该函数vim
[root@cnsz142728 scripts]# vim number.sh #!/bin/bash function test(){ read -p "Please input number:" num #read num if [ $num -ge 0 -a $num -lt 10 ];then return 0 fi if [ $num -ge 10 -a $num -lt 20 ];then return 1 fi if [ $num -ge 20 -a $num -lt 30 ];then return 2 fi return 3 } echo "Start calling function" test park=$? if [ $park -eq 0 ];then echo "The number is between [0,10)" elif [ $park -eq 1 ];then echo "The number is between [10,20)" elif [ $park -eq 2 ];then echo "The number is between [20,30)" else echo " unknown number" fi "number.sh" 31L, 702C written [root@cnsz142728 scripts]# ./number.sh Start calling function Please input number:2 The number is between [0,10) [root@cnsz142728 scripts]# ./number.sh Start calling function Please input number:44 unknown number [root@cnsz142728 scripts]# ./number.sh Start calling function Please input number:22 The number is between [20,30) [root@cnsz142728 scripts]# ./number.sh Start calling function Please input number:15 The number is between [10,20) [root@cnsz142728 scripts]#
该脚本运用if 语句,if elif ..else以及调用函数和返回值bash
3.functions函数库,该函数库总共有27个函数函数
[root@cnsz142728 September]# vim functions.sh #/bin/bash . /etc/init.d/functions confirm ITEM if [[ $? -le 0 ]];then echo "ITEM confirmed" else echo "ITEM is not comfirmed" fi "functions.sh" 9L, 137C written [root@cnsz142728 September]# ./functions.sh Start service ITEM (Y)es/(N)o/(C)ontinue? [Y] Y ITEM confirmed [root@cnsz142728 September]# ./functions.sh Start service ITEM (Y)es/(N)o/(C)ontinue? [Y] N ITEM is not comfirmed