语法
1)
函数名称 () {
statement
statement
}
2)
function 函数名称 {
statement
statement
}
调用函数 函数名称
也可以通过位置变量的方式给函数传递参数
用法:function+case 目录管理
[root@Labatt shell]# cat function.sh
#!/bin/bash
create_dir (){
echo 1
read -p "please input dir_name " dir
if [ -e $dir ];then
echo "$dir exis"
else
mkdir -p $dir
fi
}
remove_dir(){
echo 2
read -p "please input dir_name " dir
if [ -e $dir ];then
rm -rf $dir
fi
}
cat << eof
========================
目录管理
1、创建目录
2、删除目录
3、退出脚本
eof
while true; do
read -p "please input your choice " choice
case $choice in
1)
create_dir
;;
2)
remove_dir
;;
3)
exit 0
;;
*)
echo "input error"
;;
esac
done
用法二:写脚本引用某个脚本的函数source或者.
[root@Labatt shell]# cat function2.sh
#!/bin/bash
#source /admin/shell/function.sh &>/dev/null
. /admin/shell/function.sh &>/dev/null
create_dir
remove_dir
用法三:应用到服务管理
[root@Labatt init.d]# cat nginx
#!/bin/bash
nginx_cmd=/usr/local/service/nginx/sbin/nginx
nginx_conf=/usr/local/service/nginx/conf/nginx.conf
nginx_pid_file=/usr/local/service/nginx/logs/nginx.pid
start() {
$nginx_cmd
if [ $? -eq 0 ];then
echo "服务nginx启动..."
else
echo "start failed"
fi
}
stop() {
$nginx_cmd -s stop
}
reload() {
if $nginx_cmd -t &> /dev/null;then
$nginx_cmd -s reload
else
$nginx_cmd -t
fi
}
status() {
if [ -e $nginx_pid_file ];then
echo "nginx is started pid is $(cat $nginx_pid_file)"
else
echo "nginx is stop"
fi
}
restart() {
$nginx_cmd -s stop && $nginx_cmd
}
if [ -z $1 ];then
echo "使用 {start;stop;status;reload;restart}"
exit 9
fi
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
reload)
reload
;;
status)
status
;;
*)
echo "使用 {start;stop;status;reload;restart}"
exit 8
esac