创建函数

基本的函数脚本

创建函数:

function name{
    commands
}

使用函数:指定函数名即可

ubuntu@TOS:~/ShellTest/ch17$ cat test1.sh 
#!/bin/bash

function func1 {
    echo "This is an example of a fucntion"
}

count=1
while [ $count -le 5 ]
do
    func1
    count=$[ $count + 1 ]
done

echo "end of the loop"
func1
echo "end of script"

ubuntu@TOS:~/ShellTest/ch17$ ./test1.sh 
This is an example of a fucntion
This is an example of a fucntion
This is an example of a fucntion
This is an example of a fucntion
This is an example of a fucntion
end of the loop
This is an example of a fucntion
end of script

返回值:bash shell会把函数当作一个小型脚本,运行结束时会返回一个退出状态码。默认情况下,函数的退出状态码是函数中最后一条命令返回的退出状态码。在函数执行结束后,可以用标准变量$?来确定函数的退出状态码。

ubuntu@TOS:~/ShellTest/ch17$ cat test2.sh 
#!/bin/bash

func1() {
    echo "tring to display a non-exitent file"
    ls -l badfile
}

echo "testing the function: "
func1
echo "The exit status is: $?"

ubuntu@TOS:~/ShellTest/ch17$ ./test2.sh 
testing the function: 
tring to display a non-exitent file
ls: cannot access badfile: No such file or directory
The exit status is: 2
posted @ 2017-09-09 17:22  Charlyhash  阅读(126)  评论(0)    收藏  举报