function 函数名 { 命令序列 } 或 函数名() { 命令序列 }
函数名 [参数1] [参数2]
1、函数一结束就取返回值,因为s?变量只返回执行的最后一条命令的退出状态码
2、退出状态码必须是0-255,超出时值将除以256取余
#!/bin/bash function db1 { read -p "please enter:" value return $[$value * 2] } db1 echo $?
#!/bin/bash db1() { read -p "please enter:" value echo $[$value * 2] } result=`db1` echo $result
#!/bin/bash sum1() { sum=$[$1 + $2] echo $sum } read -p "enter the first parameter:" first read -p "enter the second parameter:" second sum1 $first $second
#!/bin/bash sum2() { sum=$[$1 + $2] echo $sum } sum2 $1 $2
#!/bin/bash myfun() { local i i=8 echo $i } i=9 myfun echo $i
#!/bin/bash fact(){ if [ $1 -eq 1 ];then echo 1 else local temp=$[ $1 - 1 ] local result=$(fact $temp) echo $[ $1 * $result ] fi } read -p "please enter:" n result=$(fact $n) echo $result
mkdir -p /root/bin/aa/bb/cc/dd ; touch /root/bin/aa/bb/cc/dd/abc.txt,
输出环境变量PATH所包含的所有目录以及其中的子目录和所有不可执行文件
#!/bin/bash list_files() { for i in $(ls $1) do if [ -d "$1/$i" ];then echo "$2$i" list_files "$1/$i" " $2" else if [ ! -x "$1/$i" ];then echo "$2$i" fi fi done } OLDIFS=$IFS IFS=$IFS':' for folder in $PATH do echo $folder list_files "$folder" " " done IFS=$OLDIFS
vim myfuncs.sh
#!/bin/bash fact() { if [ $1 -eq 1 -o $1 -eq 0 ];then echo 1 else local temp=$[$1 - 1] local result=$(fact $temp) echo $[$1 * $result] fi } add() { echo $[$1 + $2] } sub() { echo $[$1 - $2] } mult() { echo $[$1 * $2] } div() { if [ $2 -ne 0 ];then echo $[$1 / $2] else echo "The dividend cannot be 0" fi }
vim testfuncs.sh
. myfuncs.sh v1=$1 v2=$2 res1=$(add $v1 $v2) res2=$(sub $v1 $v2) res3=$(mult $v1 $v2) res4=$(div $v1 $v2) res5=$(fact $v1) res6=$(fact $v2) echo "The result of addition is $res1" echo "The result of subtraction is $res2" echo "The result of multiplication is $res3" echo "The result of division is $res4" echo "$1 factorial is $res5" echo "$2 factorial is $res6"