写一个shell脚本 脚本输入参数:mysql端口号,mysql密码,mysql用户,mysql所在ip,MySQL的表,mysql表的列名 步骤一,登录mysql获取表的结构 步骤二,根据步骤一中获取的表结构,在内容中去掉参数中的列名定义。 步骤三,登录mysql,根据步骤二中修改后的表定义,重建这张表
时间: 2024-03-16 20:47:17 浏览: 54
好的,以下是脚本代码:
```bash
#!/bin/bash
# 获取输入参数
port=$1
password=$2
user=$3
ip=$4
table=$5
column=$6
# 步骤一:登录mysql获取表的结构
structure=$(mysql -h ${ip} -u ${user} -p${password} -P ${port} -e "desc ${table}")
# 步骤二:在内容中去掉参数中的列名定义
new_structure=$(echo "${structure}" | grep -v "${column}")
# 步骤三:根据步骤二中修改后的表定义,重建这张表
mysql -h ${ip} -u ${user} -p${password} -P ${port} -e "drop table if exists ${table}"
mysql -h ${ip} -u ${user} -p${password} -P ${port} -e "create table ${table} (${new_structure})"
```
注意:在执行脚本时,需要给予脚本执行权限,即执行 `chmod +x 脚本文件名`。另外,脚本中的 MySQL 登录信息需要根据实际情况进行修改。
相关问题
写一个shell脚本 脚本输入参数:mysql端口号,mysql密码,mysql所在ip,MySQL的表(多个表逗号间隔),mysql表的列名(多个列逗号间隔) 脚本要求:循环判断mysql是否可登录,当可登录删除mysql表的列,并切换到MySQL用户,重启数据库,并重建这些表
好的,我来为您编写这个脚本。
```bash
#!/bin/bash
# 检查参数是否正确
if [ $# -lt 5 ]; then
echo "Usage: $0 <mysql_port> <mysql_password> <mysql_host> <mysql_tables> <mysql_columns>"
exit 1
fi
# 获取参数
mysql_port=$1
mysql_password=$2
mysql_host=$3
mysql_tables=$4
mysql_columns=$5
# 循环判断mysql是否可登录
while ! mysqladmin ping -h$mysql_host -P$mysql_port -p$mysql_password --silent; do
echo "MySQL is not available, waiting for 5 seconds..."
sleep 5
done
# 删除mysql表的列
mysql -h$mysql_host -P$mysql_port -p$mysql_password << EOF
USE mysql;
ALTER TABLE $mysql_tables DROP COLUMN $mysql_columns;
EOF
# 切换到MySQL用户
sudo -u mysql /etc/init.d/mysql restart
# 重建这些表
mysql -h$mysql_host -P$mysql_port -p$mysql_password << EOF
USE mysql;
DROP TABLE IF EXISTS $mysql_tables;
CREATE TABLE $mysql_tables (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id));
EOF
echo "Done."
```
使用方法:
```bash
./script.sh <mysql_port> <mysql_password> <mysql_host> <mysql_tables> <mysql_columns>
```
其中,`<mysql_tables>` 和 `<mysql_columns>` 都可以使用逗号分隔多个表或列。例如:
```bash
./script.sh 3306 mypassword 127.0.0.1 db1.table1,db2.table2 column1,column2,column3
```
这个脚本会不断地检查 MySQL 是否可登录,如果不可登录,则会等待 5 秒钟后再次尝试。如果 MySQL 可登录,则会删除指定表的指定列,然后切换到 MySQL 用户,重启数据库,最后重新创建指定的表。
shell脚本连接MySQL 指定端口号
在shell脚本中连接MySQL指定端口号,可以使用以下命令:
```
mysql -h 主机名 -P 端口号 -u 用户名 -p
```
其中,-h 参数指定主机名或IP地址,-P 参数指定端口号,-u 参数指定用户名,-p 参数表示需要输入密码进行连接。连接成功后会进入 MySQL 命令行模式,可以进行数据库操作。如果需要执行 SQL 脚本,可以使用以下命令:
```
mysql -h 主机名 -P 端口号 -u 用户名 -p 数据库名 < 脚本文件名
```
该命令会将脚本文件中的 SQL 语句执行到指定的数据库中。
阅读全文
相关推荐
















