linux shell script中的函数简介

        懂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函数就是这么简单, 你想任性一点, 那也可以。

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值