LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 118|回复: 0

SysV /etc/rc.d/init.d/functions脚本源码分析 - confirm函数

[复制链接]
发表于 2023-12-18 15:26:14 | 显示全部楼层 |阅读模式

confirm函数
这个函数一般用不上,因为脚本本来就是为了避免交互式的。在CentOS 7的functions中已经删除了该函数定义语句。不过,借鉴下它的处理方法还是不错的。

以下摘自CentOS 6.6的/etc/init.d/functions文件。

# returns OK if $1 contains $2
strstr() {
  [ "${1#*$2*}" = "$1" ] && return 1   # 参数$1中不包含$2时,返回1,否则返回0
  return 0
}

# Confirm whether we really want to run this service
confirm() {
  [ -x /bin/plymouth ] && /bin/plymouth --hide-splash
  while : ; do
      echo -n $"Start service $1 (Y)es/(N)o/(C)ontinue? [Y] "
      read answer
      if strstr $"yY" "$answer" || [ "$answer" = "" ] ; then
         return 0
      elif strstr $"cC" "$answer" ; then
     rm -f /var/run/confirm
     [ -x /bin/plymouth ] && /bin/plymouth --show-splash
         return 2
      elif strstr $"nN" "$answer" ; then
         return 1
      fi
  done
}
第一个函数strstr的作用是判断第一个参数$1中是否包含了$2,如果包含了则返回状态码0。这函数也是一个不错的技巧。

第二个函数confirm的作用是根据交互式输入的值返回不同的状态码,如果输入的是y或Y或不输入时,返回0。输入的是c或C时,返回状态码2,输入的是n或N时返回状态码1。

于是可以根据confirm的状态值决定是否要继续执行某个程序。

用法和效果如下:

[root@xuexi ~]# confirm
Start service  (Y)es/(N)o/(C)ontinue? [Y] Y
[root@xuexi ~]# echo $?
0
[root@xuexi ~]# confirm
Start service  (Y)es/(N)o/(C)ontinue? [Y]
[root@xuexi ~]# echo $?
0
[root@xuexi ~]# confirm
Start service  (Y)es/(N)o/(C)ontinue? [Y] n
[root@xuexi ~]# echo $?
1
[root@xuexi ~]# confirm
Start service  (Y)es/(N)o/(C)ontinue? [Y] c
[root@xuexi ~]# echo $?
2
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表