1. 编写函数,实现OS的版本判断
答: #!/bin/bash os_release(){ cat /etc/os-release | sed -rn '1s@NAME="([[:alpha:]]+) Linux"@\1@p' }
2. 编写函数,实现取出当前系统eth0的IP地址
答: ens33_ip(){ ip a | grep "ens33"| sed -rn 's@.*inet (([0-9]{1,3}\.){3}[0-9]{1,3}\/([0-9]+)).*@\1@p' }
3. 编写函数,实现打印绿色OK和红色FAILED
4. 编写函数,实现判断是否无位置参数,如无参数,提示错误
答: parameter(){ if [ $# -eq 0 ];then echo "Error" return 1 fi } 5. 编写函数,实现两个数字做为参数,返回最大值
答: MAXNUM(){ if [[ $1 -lt $2]];then echo "$2" else echo "$1" fi }
6. 编写服务脚本/root/bin/testsrv.sh,完成如下要求 (1) 脚本可接受参数:start, stop, restart, status (2) 如果参数非此四者之一,提示使用格式后报错退出 (3) 如是start:则创建/var/lock/subsys/SCRIPT_NAME, 并显示“启动成功” 考虑:如果事先已经启动过一次,该如何处理? (4) 如是stop:则删除/var/lock/subsys/SCRIPT_NAME, 并显示“停止完成” 考虑:如果事先已然停止过了,该如何处理? (5) 如是restart,则先stop, 再start 考虑:如果本来没有start,如何处理? (6) 如是status, 则如果/var/lock/subsys/SCRIPT_NAME文件存在,则显示“SCRIPT_NAME is running...” (7)在所有模式下禁止启动该服务,可用chkconfig 和 service命令管理 说明:SCRIPT_NAME为当前脚本名
答:脚本如下
#!/bin/bash start(){ ??????? touch /var/lock/subsys/$0 ?? ??? ?echo "start success" }
stop(){ ?? ??? ?rm -f /var/lock/subsys/$0 ?? ??? ?echo "stop success" } status(){ if [ -f /var/lock/subsys/$0 ];then ?? ??? ??? ??? ?echo “$0 is running...” ??????? else ??????????????? echo “$0 is stopped...” fi }
if [ $# -eq 0 ];then ??????? echo "error" ??????? exit else ??????? if [ $1 = "start" ];then ?? ??? ??? ?if [ -f /var/lock/subsys/$0 ];then ?? ??? ??? ??? ?echo "service is running" ?? ??? ??? ?else ?? ??? ??? ??? ?start ?? ??? ??? ?fi ??????? elif [ $1 = "stop" ];then ??????????? stop ??????? elif [ $1 = "restart" ];then ??????????? if [ -f /var/lock/subsys/$0 ];then ?? ??? ??? ??? ?stop ?? ??? ??? ??? ?start ?? ??? ??? ?else ?? ??? ??? ??? ?start ?? ??? ??? ?fi ??????? elif [ $1 = "status" ];then ??????????? status ??????? fi fi
|