懂C语言的人, 没有不知道函数的, 下面我们来看看linux shell script中的函数, 其实也很简单:
[taoge@localhost learn_shell]$ ls
a.sh
[taoge@localhost learn_shell]$ cat a.sh
#! /bin/bash
fun()
{
echo "calling fun"
}
echo "begin ---"
fun # call fun
echo "end ---"
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$ ./a.sh
begin ---
calling fun
end ---
[taoge@localhost learn_shell]$
可以看到, 调用的时候, 不需要写fun(), 而应该用fun, 而且fun函数在定义的时候, 也不需要返回值类型。
再看:
[taoge@localhost learn_shell]$ ls
a.sh
[taoge@localhost learn_shell]$ cat a.sh
#! /bin/bash
fun()
{
echo $1
}
echo "begin ---"
fun # call fun
echo "end ---"
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$ ./a.sh good
begin ---
end ---
[taoge@localhost learn_shell]$
可以看到, 调用fun的时候, 没有传递参数, 所以fun中实际并不能访问到$1
那行, 我们来传一下参数:
[taoge@localhost learn_shell]$ ls
a.sh
[taoge@localhost learn_shell]$ cat a.sh
#! /bin/bash
fun()
{
echo $0
echo $1
}
echo "begin ---"
fun "$1" # call fun
echo "end ---"
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$ ./a.sh
begin ---
./a.sh
end ---
[taoge@localhost learn_shell]$ ./a.sh good
begin ---
./a.sh
good
end ---
可见, 参数传递成功。
最后, 我们来看看return, 注意return 0表示成功:
[taoge@localhost learn_shell]$ ls
a.sh
[taoge@localhost learn_shell]$ cat a.sh
#! /bin/bash
fun()
{
return 0
}
echo "begin ---"
if fun
then
echo good
else
echo bad
fi
echo "end ---"
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$ ./a.sh
begin ---
good
end ---
[taoge@localhost learn_shell]$
linux shell script函数就是这么简单, 你想任性一点, 那也可以。