千家信息网

shell循环和函数引用

发表于:2025-02-03 作者:千家信息网编辑
千家信息网最后更新 2025年02月03日,#!/bin/bash#菜单function menu(){echo -e "\t\t\t************************"echo -e "\t\t\t* 操作数据库
千家信息网最后更新 2025年02月03日shell循环和函数引用
#!/bin/bash#菜单function menu(){echo -e "\t\t\t************************"echo -e "\t\t\t*       操作数据库     *"echo -e "\t\t\t************************"echo -e "\t\t\t* 1、登录数据库        *"   echo -e "\t\t\t* 2、创建用户或增加权限*"echo -e "\t\t\t* 3、sql语句操作数据库 *"echo -e "\t\t\t* 4、更改用户密码      *"echo -e "\t\t\t* 0、退出              *"echo -e "\t\t\t************************"}#输入mysql的用户名和密码function input(){echo -e "\t\t\t请登录数据库"read -p "请输入mysql用户名:" userread -s -p "请输入mysql的密码:" passwd}#判断输入的用户名密码是否正确function panduan(){mysql -u$user -p$passwd -e exit 1>/dev/null 2>&1if [ $?!= 0 ]thenecho -e "\n\t\t\t用户名或密码错误,请重新输入!"inputelseecho -e "\n\t\t\t数据库登录成功!"fi}#创建用户并授权function createuser(){echo -e "已存在的用户如下,如果输入的用户已存在,则增加该用户到权限"mysql -u$user -p$passwd -e "select user,host from mysql.user;"read -p "请输入要创建的用户名:" newuserread -s -p "请输入新用户的密码:" newpasswdecho -e "请输入此用户的主机名(%代表所有的主机都能用此账户访问数据库,具体到某几个主机名中间用英文的逗号隔开,如localhost,192.168.1.1):"read hostnameecho -e "请输入授予此用户操作数据库的权限(all代表全部,具体到某几个权限中间用英文的逗号隔开,如create,select):" read grantecho -e "请输入授予此用户的访问的库和表的权限(*.*代表全部的库和表,具体到某几个库中间用英文的逗号隔开,如database1.table1,database2.table2):"read databasemysql -u$user -p$passwd -e "grant $grant on $database to '$newuser'@'$hostname' identified by '$newpasswd';" 2>/tmp/error.txtif [ -s /tmp/error.txt ]thenecho -e "\t\t数据库的权限或库名、表名输入错误!"elseecho -e "\n\t\t\t用户创建成功!"fi}#命令行操作数据库function orders(){while truedoecho -e "\n"echo -e "请输入mysql语句:"read ordermysql -u$user -p$passwd -e "$order" 2>/dev/nullif [ $?!=0 ]thenecho -e "\t\t\tsql语句输入错误!"fidone}#修改密码function change(){echo -e "数据库中已存在的用户如下:"tuser=`mysql -u$user -p$passwd -e "select distinct User from mysql.user;"|awk '{print $1}'|sed -n '2,$p'`echo $tuserwhile truedoecho -e "请输入要修改的用户名:"read cuserecho -e "请输入新密码"read -s cpasswdecho -e "请再次输入新密码"read -s zpasswdecho $tuser|grep $cuser>/tmp/tuser.txtif [ "$cpasswd" = ""$zpasswd"" -a -s /tmp/tuser.txt ]thenmysql -u$user -p$passwd </tmp/mysql.txtif [ -s /tmp/mysql.txt ]thenecho -e "\n\t\t\t用户名或密码错误,请重新输入!"elsebreakfidone;;2)inputpanduancreateuser;;3)inputorders;;4)inputpanduanchange;;0)exit 0;;*)echo -e "\t\t\t请输入有效数字!";;esacdone


0