Linux shell编程之shell函数

编写funexpr.sh脚本
1)任务需求及思路分析
用户在执行时提供2个整数参数,这个可以通过位置变量$1、$2读入。
针对给定的两个整数,四则运算可以视为一组操作,可以定义为一个函数,依次负责加减乘除运算并输出结果。
调用函数时,将用户提供的两个参数传递给函数处理。
2)根据实现思路编写脚本文件

[root@svr5 ~]# vim funexpr.sh
#!/bin/bash
myexpr() {
    echo "$1 + $2 = $[$1+$2]"
    echo "$1 - $2 = $[$1-$2]"
    echo "$1 * $2 = $[$1*$2]"
    echo "$1 / $2 = $[$1/$2]"
}
myexpr $1 $2

[root@svr5 ~]# chmod +x funexpr.sh

3)测试脚本执行效果

[root@svr5 ~]# ./funexpr.sh  43  21
43 + 21 = 64
43 - 21 = 22
43 * 21 = 903
43 / 21 = 2

[root@svr5 ~]# ./funexpr.sh 1234 567 
1234 + 567 = 1801
1234 - 567 = 667
1234 * 567 = 699678
1234 / 567 = 2

编写myhttpd服务脚本
1)任务需求及思路分析
作为系统服务脚本,应该将脚本复制到/etc/init.d/目录下,还应该在脚本开头添加chkconfig管理参数、description服务描述。服务脚本的控制参数通过位置变量 $1 传入,使用case分支进行识别、执行相应的操作。
简单起见,start、stop操作可直接调用源码安装的httpd的控制程序apachectl,通过if判断执行结果,分别给出“确定”或“失败”的提示。
为了查看及使用方便,将上述start、stop操作分别定义为函数。restart操作则直接先调stop再调start。对于case未识别的其他参数,给出脚本的正确用法。
2)根据实现思路编写脚本文件

[root@svr5 ~]# vim /etc/init.d/myhttpd
#!/bin/bash
# chkconfig: - 85 24
# description: Startup script for httpd server. (for Test only)
PROG="/usr/local/httpd/bin/apachectl"  		//指定web控制程序路径
start() {  									//定义start函数,用来启动服务
    echo -n "正在启动httpd服务 ... "
    if $PROG start &> /dev/null  			//启动服务并判断是否成功
    then
        echo -e "\t\t\t\t[确定]"  			//-e启用转义符,\t表示一个制表位
    else
        echo -e "\t\t\t\t[失败]"
    fi
}
stop() {  									//定义stop函数,用来启动服务
    echo -n "正在关闭httpd服务 ... "
    if $PROG stop &> /dev/null  				//启动服务并判断是否成功
    then
        echo -e "\t\t\t\t[确定]"
    else
        echo -e "\t\t\t\t[失败]"
    fi
}

case "$1" in
start)
    start  									//调用start函数
    ;;
stop)
    stop  									//调用stop函数
    ;;
restart)
    $0 stop
    $0 start
    ;;
*)
    echo "用法: $0 {start|stop|restart}"
    exit 1
esac
[root@svr5 ~]# chmod +x /etc/init.d/myhttpd

3)验证、测试脚本
确认对start控制参数的响应:

[root@svr5 ~]# netstat -anptl | grep httpd  	//确认httpd网络服务未监听
[root@svr5 ~]# service myhttpd start
正在启动httpd服务 ...                           [确定]
[root@svr5 ~]# netstat -anptl | grep httpd  	//再次检查httpd服务已在监听
tcp        0      0 :::80       :::*         LISTEN      16011/httpd
确认对stop控制参数的响应:
[root@svr5 ~]# service myhttpd stop
正在关闭httpd服务 ...                           [确定]
[root@svr5 ~]# netstat -anptl | grep httpd  	//检查已无httpd监听
[root@svr5 ~]#
确认对未识别的控制参数的响应:
[root@svr5 ~]# service myhttpd status
用法: /etc/init.d/myhttpd {start|stop|restart}

4)添加myhttpd服务
使用chkconfig --add添加myhttpd服务,确认结果:

[root@svr5 ~]# chkconfig --add myhttpd
[root@svr5 ~]# chkconfig --list myhttpd
myhttpd         0:关闭  1:关闭  2:关闭  3:关闭  4:关闭  5:关闭  6:关闭

如果已经有其他关于httpd服务的自启脚本,这里建议就不要将myhttpd也设为自动开启了,否则会出现端口冲突等故障。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值