mysql - 在 bash 脚本中创建 SQL 脚本
问题描述
我正在尝试使用基本的 bash 脚本引导 mysql
cat <<EoF > /tmp/mysql-load-table.sql
CREATE DATABASE IF NOT EXISTS `web_customer_tracker`;
USE `web_customer_tracker`;
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(45) DEFAULT NULL,
`last_name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
LOCK TABLES `customer` WRITE;
INSERT INTO `customer` VALUES
(1,'JeanLuc','Picard','picard@tng.com'),
(2,'William','Riker','riker@tng.com'),
(3,'Beverly','Crusher','crusher@tng.com'),
(4,'Geordi','LaForge','laforge@tng.com'),
(5,'Data','Android','data@tng.com');
UNLOCK TABLES;
EoF
如果我将这些命令直接输入到 MySQL 中,上述工作正常,但是当我将其作为 bash 脚本的一部分运行时,我得到以下错误
-bash: web_customer_tracker: command not found
-bash: web_customer_tracker: command not found
-bash: customer: command not found
-bash: customer: command not found
-bash: customer: command not found
-bash: first_name: command not found
-bash: last_name: command not found
-bash: email: command not found
-bash: customer: command not found
-bash: customer: command not found
-bash: customer: command not found
无法弄清楚我在这里缺少什么,任何帮助将不胜感激。我想将其创建为 SQL 脚本,然后将其传递给 mysql 以创建数据库并加载数据。
解决方案
引用您的 heredoc 分隔符,例如
cat <<'EoF' > /tmp/mysql-load-table.sql
CREATE DATABASE IF NOT EXISTS `web_customer_tracker`;
USE `web_customer_tracker`;
...
EoF
从man bash:
不会对 word 执行参数和变量扩展、命令替换、算术扩展或路径名扩展。如果 word 中的任何字符被引用,则分隔符是 word 上去除引号的结果,并且 here-document 中的行不展开。 如果 word 不被引用,则 here-document 的所有行都经过参数扩展、命令替换和算术扩展,字符序列 <newline> 被忽略,并且必须使用 \ 来引用字符、$ 和 `。
推荐阅读
- c++ - Windows 平台是否有等效的 INSTALL RPATH?
- mysql - 校园项目中的学生分配。循环遍历数据库中的排序对象数组,对其进行过滤并执行操作以适应学生
- java - 如何打印没有方括号的数组?
- tensorflow - 使用自定义指标加载 HDF5 检查点模型
- sql - 从另一个数组列创建连接的数组列 - postgresql
- javascript - 类中的vue3反应性
- javascript - 在自定义反应组件中获取道具值建议
- clojure - Clojure Gloss - 来自 MQTT 协议规范的可变字节整数的编解码器
- python - 围绕 cx_Oracle 库实现 python 代码的问题
- r - 如何调整预测的对数函数,使其更接近我的数据点?