美文网首页
getopts实现模拟mysql参数登录

getopts实现模拟mysql参数登录

作者: 堂哥000 | 来源:发表于2022-05-25 17:00 被阅读0次

    getopts脚本设置方式

    # ":u:p:h:P:" 中开头的:是指区分错误类型
    # u: 变量后 : 指使用时必须有参数值
    # OPTARG 是指系统内置变量
    while getopts ":u:p:h:P:" opt
    do
      case $opt in
        u)
        user=$OPTARG 
        echo "用户名: ${user}" ;;
        p)
        pwk=$OPTARG
        echo "用户密码: ${pwk} " ;;
        h)
        host=$OPTARG
        echo "连接主机IP为: ${host}" ;;
        P)
        post=$OPTARG
        echo "端口号为: ${post}" ;;
      esac
    done
    if [[ $pwk = "" ]];then 
     # -s 指静默输入, 不会在命令行显示输出内容, -p 指提示信息
      read -s -p "请输入密码:" pwk
     # -e -n 设置为了识别 \n 
      echo -e -n "\n用户密码: ${pwk} \n"   
    fi
    # 此处为模拟运行的方式,仅打印测试
    echo "mysql -u${user} -P${post} -h${host} -p${pwk}"
    

    直接填充密码型mysql -uyuanyu -P3306 -h10.10.10.10 -pyuanyu

    image.png
    回车后手动输出sh data.sh -uyuanyu -h10.10.10.10 -P3306 -p
    image.png
    另外在getopts 中未命中参数是也有相应配置,这里我省略掉了
    while getopts ":u:p:h:P:" opt
    do
      case $opt in
        u)
        user=$OPTARG 
        echo "用户名: ${user}" ;;
        ?)
           echo "无效参数"
           # 此处若有无效参数,选择直接退出
           # 若想忽略无效参数,继续运行,则将下面这行注释掉
           exit 0;
          esac
    done
    

    相关文章

      网友评论

          本文标题:getopts实现模拟mysql参数登录

          本文链接:https://www.haomeiwen.com/subject/xfzeprtx.html