shell之function

语法

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值