关于shell函数的总结

关于shell函数的总结
1.函数的写法:
methodName(){
....
}
如:
# 获取当前时间,如:2009-01-01 00:00:00
getCurrentTime()
{
current_time=`date --date="now" +%Y-%m-%d' '%H:%M:%S`;
echo $current_time;
}
2.函数返回值,利用echo返回
如上面的函数的echo $current_time;语句
3.函数的调用
现在需要调用的shell文件里用. function.sh,把方法载入,然后直接调用methodName即可,如:
. function.sh
getCurrentTime
4.带有参数的函数,如下(只传入了一个参数)使用$符号进行处理参数:
#判断文件是否存在
fileExist() {
filename=$1
if [ -e "${filename}" ]
then
echo $1 '文件存在'
else
echo $1 '文件不存在'
fi
}
5.带有参数函数的访问:
file=`fileExist first.sh`

以下为全部代码:
function.sh(函数文件)

# 获取当前时间,如:2009-01-01 00:00:00
getCurrentTime(){
current_time=`date --date="now" +%Y-%m-%d' '%H:%M:%S`;
echo $current_time;
# return $current_time;
}
#判断文件是否存在
fileExist() {
filename=$1
if [ -e "${filename}" ]
then
echo $1 '文件存在'
else
echo $1 '文件不存在'
fi
}
dateformata(){
time=$1
# echo $1|sed -n 's/ /-/p'|cut -b1-13
if [ -z "${time}" ]
then
echo 'time is error'
else
echo $time|sed -n 's/ /-/p'|cut -b1-13
fi
}

second.sh(函数调用文件)

. function.sh
getCurrentTime
s=`getCurrentTime`
file=`fileExist first.sh`
time=`dateformata "$s"`
echo $file
echo "test:" $s
echo "time:" $time

运行结果:

2009-03-18 19:27:12
first.sh 文件存在
test: 2009-03-18 19:27:12
time: 2009-03-18-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值