关于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(函数文件)
second.sh(函数调用文件)
运行结果:
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