栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

shell之function

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853565.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号